Note that there are some explanatory texts on larger screens.

plurals
  1. POdjango ModelForm save() method issue
    primarykey
    data
    text
    <p>I have a model form: </p> <pre><code>class SnippetForm(ModelForm): class Meta: model = Snippet exclude = ['author', 'slug'] </code></pre> <p>and I want to be able to edit a particular instance by using this: </p> <pre><code>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)) </code></pre> <p>Notice that at the line </p> <p><code>form = SnippetForm(data=request.POST, instance=snippet)</code></p> <p>, I created a form that use the data supplied from the user, and bound it with the instance found using the primary key (received from the url). According to <a href="http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#the-save-method" rel="nofollow">django documentation</a>, when I call save() the existing instance should be updated with POSTED data. Instead, what I see is a new object is created and saved into the database. What went wrong? Thanks a lot. </p> <p>[Edit] This is really embarrassed. The code indeed has nothing wrong with it. The only thing that messed up the whole thing was the action I put in the template (as I use a same template for add and edit a snippet)....Thanks a lot for your help, really appreciate that.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload