使用foreignkey渲染2个formset时,Django“ManagementForm数据丢失”

时间:2013-08-02 23:38:08

标签: html django rendering formsets

我正在尝试在1个视图中渲染2个formset并且正在获取

u'ManagementForm data is missing or has been tampered with

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

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

以下是我的views.py和html:

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

1 个答案:

答案 0 :(得分:0)

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

else:
   optionForm = OptionForm()
   outcomeForm = OutcomeForm()
   optionInlineFormSet = OptionFormSet(prefix='option')
   outcomeInlineFormSet = OutcomeFormSet(prefix='outcome')