我需要为单个视图使用自定义表单的多个表单集。我知道您需要为表单集添加前缀,以便它们不会相互冲突。但是,当我尝试为表单集添加前缀时,会引发ValidationError。
我创建表单集的方法是将表单列表传递给视图,然后使用formset_factory创建FormSets列表。然后我创建一个初始化的表单集列表。
这是我的代码:
def edit_stuff2(request, business_id, template_name="business/edit_info.html",
*args, **kwargs):
business = BusinessDoc.get(business_id)
FormSets=[]
formsets=[]
info_forms = [(EmailDocForm,'emails'), (URLDocForm,'urls')]
for form in info_forms:
FormSets.append(formset_factory(form[0], max_num =0,
can_delete=True, extra=1))
if request.user:
if request.method == "POST":
for FormSet,tup in zip(FormSets,info_forms):
FormSet.form = staticmethod(curry(tup[0], business))
formsets.append(FormSet(request.POST,prefix=tup[1],
initial = business[tup[1]]))
if formsets[-1].is_valid():
for form in formsets[-1].forms:
form.save()
#request.user.message_set.create(message=u"Check it")
formsets = []
for FormSet, tup in zip(FormSets, info_forms):
FormSet.form = staticmethod(curry(tup[0], business))
formsets.append(FormSet(prefix=tup[1], initial=business[tup[1]]))
return direct_to_template(request, template=template_name,
extra_context={'business': business,
'formsets': formsets,
'info_type': info_type})
else:
return HttpResponseRedirect(reverse('home'))