How to update an existing record, and then add a new one, which is my problem. Now I am trying to edit existing product data in the form of editing and save new changes. But instead of updated product data, I get a new product, so everything is duplicated. A new product is created instead of updated data. What can I do to solve this problem?
Here is my code:
@login_required
def edit(request, id=None):
if request.method == 'POST':
form = ProductForm(request.POST)
if form.is_valid():
product = form.save( commit=False )
product.save()
return HttpResponseRedirect( '/details/%s/' % ( product.id ) )
Eternicode, thanks for the excellent answer, now the code works fine, and the data is not duplicated, since I save the form after editing the date. Based on your answer, here is what works:
@login_required
def edit(request, id=None):
if request.method == 'POST':
product = Product.objects.get(id__exact=id)
form = ProductForm(request.POST, instance=product)
print "PRODUCT POST"
if form.is_valid():
print "Display Form"
product = form.save( commit=False )
product.save()
return HttpResponseRedirect( '/details/%s/' % ( product.id ) )
source
share