所以,总的Django Model Formset Newb问题。我正在尝试保存表单并继续收到此错误:
['ManagementForm data is missing or has been tampered with']
以下是我的TemplateView:
class AttendanceTemplate(TemplateView):
template_name = 'attendance/index.html'
def get_context_data(self, **kwargs):
context = super(AttendanceTemplate, self).get_context_data(**kwargs)
instruction = Instruction(self.request.user.username)
sections_list = self.request.GET.getlist('sections_list')
term = self.request.GET.get('term', instruction.term)
enrollments = Enrollment.objects.using('wisp').prefetch_related('profile').filter(section_id__in=['111111'], term=term)
attendanceQuery = Enrollment.objects.using('wisp').prefetch_related('student').filter(section_id__in=['111111'], term=term)
for enrollment in attendanceQuery:
attendance, created = Attendance.objects.update_or_create(
section_id=enrollment.section_id,
term=enrollment.term,
first_name=enrollment.student.first_name,
last_name=enrollment.student.last_name,
email_address=enrollment.student.email_address,
)
something = Attendance.objects.filter(section_id__in=['111111'], term=term)
formset = AttendanceFormSet(queryset=something)
combined = zip(enrollments, formset)
context['combined'] = combined
return context
以下是我尝试保存表单的方法:
def post(self, request):
formset = AttendanceFormSet(request.POST)
if formset.is_valid():
for thing in formset:
formset = thing.save()
return render_to_response("template/index.html",{'formset': formset}, RequestContext(request))
else:
return HttpResponse(error.msg)
以下是我在模板中的内容:
<form method="POST" action="">
{% csrf_token %}
{% for enrollment, form in combined %}
<div class="wrapper-formset">
<div>
{{ form.first_name.value }}
{{ form.last_name.value }}
{{ form.email_address.value }}
</div>
<div class="clear-all"></div>
</div>
{% endfor %}
<button type="submit" class="save btn btn-default">Save</button>
</form>
我保存我的表格错了吗?也许我的循环错了?另外,我更喜欢单独打印每个字段,因此使用“myform.management_Form”可能对我不起作用? (例如,myform.management_form.field_name)
答案 0 :(得分:1)
如果您单独呈现表单,则必须在模板中包含管理表单。您正在压缩表单的事实没有任何区别。
包含管理表单很简单,只需在模板中添加{% formset.management_form %}
即可。
<form method="POST" action="">
{% csrf_token %}
{{ formset.management_form }}
{% for enrollment, form in combined %}
...
要使其正常工作,您需要确保formset
位于模板上下文中,例如:
context['formset'] = formset
您可能会发现using model formsets in the template上的文档很有用。从最简单的选项{{ formset }}
开始,测试它,然后逐步自定义模板,这是一个好主意。这使得在出错时更容易调试。目前您似乎错过了{{ form.id }}
。