以下是我用于类似的情况(变量集字段集,每一个包含一组可变字段)。
我用type()
函数来建立我的Form类,BetterBaseForm
类从django-form-utils。
def makeFurnitureForm():
"""makeFurnitureForm() function will generate a form with
QuantityFurnitureFields."""
furnitures = Furniture.objects.all()
fieldsets = {}
fields = {}
for obj in furnitures:
# I used a custom Form Field, but you can use whatever you want.
field = QuantityFurnitureField(name = obj.name)
fields[obj.name] = field
if not obj.room in fieldsets.keys():
fieldsets[obj.room] = [field,]
else:
fieldsets[obj.room].append(field)
# Here I use a double list comprehension to define my fieldsets
# and the fields within.
# First item of each tuple is the fieldset name.
# Second item of each tuple is a dictionnary containing :
# -The names of the fields. (I used a list comprehension for this)
# -The legend of the fieldset.
# You also can add other meta attributes, like "description" or "classes",
# see the documentation for further informations.
# I added an example of output to show what the dic variable
# I create may look like.
dic = [(name, {"fields": [field.name for field in fieldsets[name]], "legend" : name})
for name in fieldsets.keys()]
print(dic)
# Here I return a class object that is my form class.
# It inherits from both forms.BaseForm and forms_utils.forms.BetterBaseForm.
return (type("FurnitureForm",
(forms.BaseForm, form_utils.forms.BetterBaseForm,),
{"_fieldsets" : dic, "base_fields" : fields,
"_fieldset_collection" : None, '_row_attrs' : {}}))
下面是如何dic
可能看起来像一个例子:
[('fieldset name 1',
{'legend': 'fieldset legend 2',
'fields' ['field name 1-1']}),
('fieldset name 2',
{'legend': 'fieldset legend 2',
'fields' : ['field 1-1', 'field 1-2']})]
我用BetterBaseForm
而非BetterForm
出于同样的原因this article建议使用BaseForm
而非Form
。
这篇文章很有意思,即使它很老,也解释了如何做动态表单(带有可变域设置)。它还提供了其他方法来实现动态表单。
虽然它没有解释如何使用字段集,但它激励我找到如何去做,并且原理保持不变。
在视图中使用它很简单:
return (render(request,'main/form-template.html', {"form" : (makeFurnitureForm())()}))
,并在模板:
<form method="POST" name="myform" action=".">
{% csrf_token %}
<div>
{% for fieldset in form.fieldsets %}
<fieldset>
<legend>{{ fieldset.legend }}</legend>
{% for field in fieldset %}
<div>
{% include "main/furniturefieldtemplate.html" with field=field %}
</div>
{% endfor %}
</fieldset>
{% endfor %}
</div>
<input type="submit" value="Submit"/>
</form>
那岂不是更好地使用[表单集(HTTP://docs.djangoproject .com/en/dev/topics/forms/formsets /)而不是字段集?一个问题的自定义Form类(带有'prompt'属性),然后使用['initial'关键字参数]加载问题数据(http://docs.djangoproject.com/en/dev/topics/forms/formssets /#使用-初始数据上带有一个-表单集)? – 2010-04-12 21:34:14
表单集不会诀窍。至少不是给定的formset_factory。我必须能够为formset中的每个表单的实际字段构造函数提供一些参数 - 值字段的标签/提示以及choicefield的单元列表。 – 2010-04-20 04:49:02