Django ModelForm save () method problem

I have a model form:

class SnippetForm(ModelForm):
    class Meta:
        model = Snippet
        exclude = ['author', 'slug']

and I want to be able to edit a specific instance using this:

def edit_snippet(request, snippet_id):
    #look up for that snippet
    snippet = get_object_or_404(Snippet, pk=snippet_id)
    if request.user.id != snippet.author.id:
        return HttpResponseForbidden()
    if request.method == 'POST':
        form = SnippetForm(data=request.POST, instance=snippet)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect(snippet.get_absolute_url())
    else:
        form = SnippetForm(instance=snippet)
    return render_to_response(SNIPPET_EDIT_TEMPLATE,
                              {'form':form, 'add':False, 'user':request.user}, 
                              RequestContext(request))

Note that in the line

form = SnippetForm(data=request.POST, instance=snippet)

I created a form that uses the data provided by the user and associated it with the instance found using the primary key (obtained from url). According to the django documentation , when I call save (), the existing instance must be updated with POSTED data. Instead, I see that a new object is being created and stored in the database. Something went wrong? Many thanks.

[Edit] . . , , - , ( ). , .

+3
1

, . django?

.

form = SnippetForm(data=request.POST, instance=snippet, force_update=True)
+1

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


All Articles