Update data instead of creating a new row entry in django model

6 views
Skip to first unread message

Joel Mathew

unread,
Aug 26, 2018, 3:48:45 AM8/26/18
to django...@googlegroups.com
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.

Jason

unread,
Aug 26, 2018, 8:27:16 AM8/26/18
to Django users
what you should do in your post check is 

           bill_item = BillItem.objects.get(code = itemcode)
form = BillItem(request.POST, instance = bill_item)

This populates the form with the existing model instance and merges with the post data.  you then can run form.save() to persist the update to the db. 
Reply all
Reply to author
Forward
0 new messages