我有以下表格:
class PlayForwardPageForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(PlayForwardPageForm, self).__init__(*args, **kwargs)
class Meta:
model = PlayForwardPage
exclude = ( 'id',)
def save(self, *args, **kwargs):
post = super(PlayForwardPageForm, self).save(*args, **kwargs)
post.save()
并查看显示它:
object = PlayForwardPage.objects.all()[0]
form = PlayForwardPageForm(instance=object)
if request.method == "POST":
form = PlayForwardPage(data=request.POST, instance=object)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('manage_playforward',))
else:
form = PlayForwardPageForm(instance=object)
加载页面时一切正常。但是当我尝试使用更改的数据保存表单时,我得到:
'data' is an invalid keyword argument for this function
任何人都可以看到任何原因或此行为吗?
答案 0 :(得分:1)
简答:PlayForwardPage
是一个不是ModelForm
的模型。
这是更正的代码,带有一些额外的样式注释。
# Don't shadow built-ins (in your case "object")
play_forward_page = PlayForwardPage.objects.all()[0]
# Don't need this form declaration. It'll always be declared below. form = PlayForwardPageForm(instance=object)
if request.method == "POST":
# Should be a the form, not the model.
form = PlayForwardPageForm(data=request.POST, instance=play_forward_page)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('manage_playforward',))
else:
form = PlayForwardPageForm(instance=play_forward_page)
另外,你在PlayForwardPageForm中做了一些不必要的事情:
class PlayForwardPageForm(forms.ModelForm):
# This __init__ method doesn't do anything, so it's not needed.
# def __init__(self, *args, **kwargs):
# super(PlayForwardPageForm, self).__init__(*args, **kwargs)
class Meta:
model = PlayForwardPage
exclude = ( 'id',)
# You don't need this since you're not doing anything special. And in this case, saving the post twice.
# def save(self, *args, **kwargs):
# post = super(PlayForwardPageForm, self).save(*args, **kwargs)
# post.save()