django ModelForm save()方法问题 [英] django ModelForm save() method issue
问题描述
我有一个模型表格:
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))
请注意,
form = SnippetForm(data = request.POST,instance = snippet)
,我创建了一个使用用户提供的数据的表单,并将其与使用主键(从url接收)找到的实例绑定.根据 django文档,当我打电话时save()应该使用POSTED数据更新现有实例.相反,我看到的是创建了一个新对象并将其保存到数据库中.什么地方出了错?非常感谢.
, 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.
这真的很尴尬.该代码确实没有错.唯一使整个事情搞砸的是我在模板中执行的操作(因为我使用相同的模板来添加和编辑代码段)....非常感谢您的帮助,
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.
推荐答案
我不知道为什么会发生这种情况.django是什么版本?
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)
这篇关于django ModelForm save()方法问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!