I have a page for editing existing data from a model.
The model:
class billitem(models.Model):
code = models.AutoField(primary_key=True, unique=True)
name = models.CharField(max_length=35)
description = models.CharField(max_length=60, null=True)
price = models.DecimalField(decimal_places=2, max_digits=8)
The form:
class BillItem(forms.Form):
code = forms.IntegerField(max_value=100000, disabled=True)
name = forms.CharField(label='Item Name', max_length=32)
description = forms.CharField(
label='Description', max_length=57, required=False)
price = forms.DecimalField(decimal_places=2, max_digits=8)
The view is:
def edit_bill_item(request, itemcode):
if request.method == 'POST':
form = BillItem(request.POST)
code = request.POST.get('code')
name = request.POST.get('name').title()
description = request.POST.get('description')
price = request.POST.get('price')
billitem.objects.filter(code=code).update(
name=name, description=description, price=price)
msg = 'Successfully saved Billing item.'
# form = BillItem(request.POST)
return render(request, 'billing/edititem.html', {'form':
form, 'msg': msg})
else:
itemcode = int(itemcode)
item = get_object_or_404(billitem, code=itemcode)
form = BillItem(initial={
'code': item.code,
'name':
item.name,
'description': item.description,
'price': item.price
})
return render(request, 'billing/edititem.html', {'form': form})
The problem is that every time POST is submitted, another entry gets
added in the table, with a new code, instead of updating existing row.
I also tried:
item = billitem(code=code, name=name, description=description, price=price)
item.save()
Which also had the same effect.
How can I handle updation of existing data only within my model and form.