开发者

django ModelForm save() method issue

I have a model form:

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

and I want to be able to edit a particular instance by 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))

Notice that at the line

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

, 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 django documentation, 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.

[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.


I don't see why it would happen. What version of django is it?

In any case, you can manually force update passing the corresponding argument.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜