0

我正在尝试在 1 个视图中呈现 2 个表单集并得到一个

u'ManagementForm data is missing or has been tampered with

错误。网页呈现正常,当我点击提交时数据确实将值传递给数据库,但我认为我传递管理表单数据不正确。

我还想补充一点,我使用了“ https://docs.djangoproject.com/en/dev/topics/forms/formsets/ ”,但它没有提供足够的文档来传递管理表单数据。此外,我的选项和结果表单集具有相同的外键。如果您在传递管理表单数据时发现任何问题,或者代码是否有任何其他问题,请告诉我。

下面是我的views.py和html:

视图.py

def option(request):

if request.method == "POST":

   optionForm = OptionForm(request.POST)
   outcomeForm = OutcomeForm(request.POST)

   if optionForm.is_valid():
      new_option = optionForm.save()
      new_outcome = outcomeForm.save()
      optionInlineFormSet = OptionFormSet(request.POST, request.FILES, instance=new_option, prefix='option')
      outcomeInlineFormSet = OutcomeFormSet(request.POST, request.FILES, instance=new_outcome, prefix='outcome')

      if optionInlineFormSet.is_valid() and outcomeInlineFormSet.is_valid:
         optionInlineFormSet.save()
         outcomeInlineForSet.save()
         return HttpResponseRedirect(reverse(outcome))

else:
   optionForm = OptionForm()
   outcomeForm = OutcomeForm()
   optionInlineFormSet = OptionFormSet()
   outcomeInlineFormSet = OutcomeFormSet()
return render_to_response("option.html", {'optionForm': optionForm, 'outcomeForm': outcomeForm, 'optionInlineFormSet': optionInlineFormSet, 'outcomeInlineFormSet': outcomeInlineFormSet}, context_instance=RequestContext(request))

html:

<form class="option_form" action="{% url option %}" method="post">{% csrf_token %}

{{ optionInlineFormSet.management_form }}
{{ outcomeInlineFormSet.management_form }}
{{ optionForm.as_table }}
{{ outcomeForm.as_table}}

<input type="submit" name="submit" value="Submit" class="button">
</form>
4

1 回答 1

0

找到了答案。您需要为 InlineFormsets 添加前缀,以免它们相互冲突。这是我的改变:

else:
   optionForm = OptionForm()
   outcomeForm = OutcomeForm()
   optionInlineFormSet = OptionFormSet(prefix='option')
   outcomeInlineFormSet = OutcomeFormSet(prefix='outcome')
于 2013-08-03T17:01:18.320 回答