我有用例,当一个formset没有在页面中呈现时。在这种情况下,request.POST
不包含管理数据。
如何手动添加缺少的管理数据? request.POST
QueryDict是只读的。
正如答案所示,我用过:
request_post_copy = request.POST.copy()
if not request_post_copy.has_key('form-TOTAL_FORMS'):
request_post_copy.update({
'form-TOTAL_FORMS': 0,
'form-INITIAL_FORMS': 0,
'form-MAX_NUM_FORMS': 1000,
})
答案 0 :(得分:3)
如果错误是缺少管理表单数据,则缺少管理表单数据。
看看这个: https://docs.djangoproject.com/en/dev/topics/forms/formsets/#using-a-formset-in-views-and-templates
在示例中,他们使用它来显示其他字段:
{{ formset.management_form }}
如果这些字段丢失,那么您会收到错误。
修改强>
如果要手动将管理字段添加到数据,则需要为以下字段添加3个键/值对:
<input type="hidden" name="form-TOTAL_FORMS" value="3" id="id_form-TOTAL_FORMS" />
<input type="hidden" name="form-INITIAL_FORMS" value="3" id="id_form-INITIAL_FORMS" />
<input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
做这样的事情:
my_post_dict = request.POST.copy()
my_post_dict['form-TOTAL_FORMS'] = value
my_post_dict['form-INITIAL_FORMS'] = value
my_post_dict['form-MAX_NUM_FORMS'] = value
myformset = MyFormSet(my_post_dict)