处理多种形式的最佳方法是什么?我想将几种形式合二为一。例如,我想将ImangeFormSet和EntryForm组合成一个表单:
class ImageForm(forms.Form):
image = forms.ImageField()
ImageFormSet = formset_factory(ImageForm)
class EntryForm(forms.Form):
title = forms.CharField(max_length=100)
result_form = combine(EntryForm, ImageFormSet) # here it goes
我发现2年前的演示文稿介绍了multipleform_factory()方法,但我不确定这是最好的方法:http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth
答案 0 :(得分:4)
一个想法(没有检查它是否有效):
class MySuperForm(CombinedForm):
includes = (ImageForm, EntryForm, )
您see here如何构建表单。您可以通过从BaseForm扩展并提供另一个__metaclass__
来创建自己的表单。
class CombinedForm(BaseForm):
__metaclass__ = DeclarativeFieldsMetaclassFromMultipleClasses
在DeclarativeFieldsMetaclassFromMultipleClasses中,您基本上与here相同,除了您总结来自
上的类的声明字段class DeclarativeFieldsMetaclassFromMultipleClasses(type):
def __new__(cls, name, bases, attrs):
for clazz in attrs['includes']:
attrs['base_fields'] += get_declared_fields(bases, clazz.attrs)
new_class = super(DeclarativeFieldsMetaclassFromMultipleClasses,cls).__new__(cls, name, bases, attrs)
if 'media' not in attrs:
new_class.media = media_property(new_class)
return new_class
答案 1 :(得分:3)
在模板中放置了多少表单并不重要,因为单个表单不会呈现表单标记。所以,你的模板就像这样
<form id='xxxx' action='' method=POST>
{{my_first_formset}}
{{my_second_form}}
</form>
并在view.py
中my_formset = MyFormset(request.POST)
my_form = MyForm(request.POST)
if my_formset.is_valid() and my_form.is_valid():
process...