以下是我用於類似的情況(變量集字段集,每一個包含一組可變字段)。
我用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