Django Change form data: data is duplicated, not updated

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 ) ) 
+3
source share
2

, instance kwarg . :

>>> 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)
+8

, . !

0

Source: https://habr.com/ru/post/1774448/


All Articles