django ModelForm save() method issue

徘徊边缘 提交于 2019-12-23 19:28:06

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/4743967/django-modelform-save-method-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!