Search code examples
pythondjango-modelsdjango-templatesforeign-keysinstance

Django ValueError: Cannot assign must be an instance by models


I have two models Tax_settings and Item_Creation I wish to use tax_id from Tax_settings as tax_code in Item_creation. I already use tax_code as a foreign key. And now I am performing a actions on it in templates to get a list of tax_code. But getting this error

models.py

class Tax_Settings(models.Model):
    tax_id = models.IntegerField()
    name = models.CharField(max_length=50)
    tax_description = models.CharField(max_length=50)
    
    class Meta:
        verbose_name = "tax_id"
    def __str__(self):
        return self.tax_id
    
class Item_Creation(models.Model):
    item=models.CharField(max_length=50)
    hsn=models.IntegerField()
    item_code = models.IntegerField()
    item_description = models.CharField(max_length=50)
    unit = models.IntegerField()
    tax_code = models.ForeignKey(Tax_Settings,on_delete=models.CASCADE)

views.py

def item_creation(request):
    get_tax_code=Tax_Settings.objects.values_list('tax_id')[0]
    print(get_tax_code)
    
    if request.method == 'POST':
        item = request.POST['item']
        hsn = request.POST['hsn']
        item_code=request.POST['item_code']
        item_description=request.POST['item_description']
        unit=request.POST['unit']
        tax_code = request.POST['tax_code']
        
        item_details = Item_Creation.objects.create(item=item, hsn=hsn, item_code=item_code,item_description=item_description, unit=unit, tax_code=tax_code)
        item_details.save()
        print("item_details",item_details)
        return render(request,"settings/item-creation.html")
    return render(request,"settings/item-creation.html",{'get_tax':get_tax_code})

item-creation.html

<div class="col-md mb-2">
     <select  id="tax-code" class="form-control" name="tax_code" >
           <option value="">Select Tax Code</option>
                 {% if get_tax %}
                      {% for t in get_tax %}
                          <option value="{{t}}">{{t}}</option>
                      {% endfor %}
                {% endif %}
     </select>

enter image description here


Solution

  • Here the problem is your have to make your tax_id as your primary key unless it will take the 'id' (which is primary key automatically created because you did not create a primary key).

    Edit your tax_id to tax_id = models.IntegerField(primary_key=True) and re migrate

    Then edit your views based on below

    tax_code = request.POST['tax_code']
    tax_obj = Tax_Settings.objects.get(tax_id=tax_code)
    item_details = Item_Creation.objects.create(item=item, hsn=hsn, item_code=item_code,item_description=item_description, unit=unit, tax_code=tax_obj)
    item_details.save()