Django多格式工厂 [英] Django multiple form factory
问题描述
处理多种形式的最佳方式是什么?我想把几种形式合并成一个。例如,我想将ImangeFormSet和EntryForm组合成一种形式:
What is the best way to deal with multiple forms? I want to combine several forms into one. For example, I want to combine ImangeFormSet and EntryForm into one form:
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
I found 2 years old presentation introducing multipleform_factory() method, but I am not sure that it's the best way: http://www.slideshare.net/kingkilr/forms-getting-your-moneys-worth
推荐答案
p>一个想法(不检查是否有效):
An idea (not checked if it works):
class MySuperForm(CombinedForm):
includes = (ImageForm, EntryForm, )
你看到这里如何构建表单。您可以通过从BaseForm扩展并提供另一个 __ metaclass __
来制作自己的表单。
You see here how the form is built. You can make your own Form by extending from BaseForm and supplying another __metaclass__
.
class CombinedForm(BaseForm):
__metaclass__ = DeclarativeFieldsMetaclassFromMultipleClasses
在DeclarativeFieldsMetaclassFromMultipleClasses中,您基本上执行与这里相同,除非你总结类中的声明字段
In DeclarativeFieldsMetaclassFromMultipleClasses you do basically the same as here, except you sum up the declared fields from the classes on
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
这篇关于Django多格式工厂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!