How can I update an existing record rather then add a new one which is my problem. Right now I'm trying to edit existing product data in the edit form and save the new changes. But instead of existing product data being updated, I get a new product, so everything is being duplicated. New product is created instead of its existing data being updated. What can I do to solve this issue?
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, thank you for the great answer, the code now works fine and data is not duplicated as I save the form after the date is edited. Based on your reply, 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 ) )
In order to update an existing object, you have to provide that object as the instance kwarg to your form. From the docs:
>>> from django.forms import ModelForm
# Create the form class.
>>> class ArticleForm(ModelForm):
... class Meta:
... model = Article
# Creating a form to add an article.
>>> form = ArticleForm()
# Creating a form to change an existing article.
>>> article = Article.objects.get(pk=1)
>>> form = ArticleForm(instance=article)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With