我有一个复杂的形式:
<<forms.py>>
class AttributeOptionForm(forms.Form):
option_name = forms.CharField(label="Attribute Option")
class AttributeForm(forms.Form):
attr_name = forms.CharField(max_length=100, label="Attribute Name")
attr_options_list = [AttributeOptionForm(), AttributeOptionForm()]
class ProjectForm(forms.Form):
name = forms.CharField(max_length=250, label="Name")
attr_form_list = [AttributeForm()]
ProjectFrom至少包含一个AttributeForm(可能在运行时增长),每个AttributeForm至少包含两个AttributeOptionForm(也可能在运行时增长)。您可以将任何AttributeForm视为具有多个答案的问题(AttributeOptionForm),我希望用户填写这些答案。
这就是我呈现ProjectForm的方式。
<<project_form.html>>
<form class="form-horizontal" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ form.name.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ form.name.label_tag }}</label>
<div class="col-sm-9">{{ form.name }}</div>
</div>
{% for attr_form in form.attr_form_list %}
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ attr_form.att_name.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ attr_form.attr_name.label_tag }}</label>
<div class="col-sm-9">{{ attr_form.attr_name }}</div>
{% for option in attr_form.attr_options_list %}
<div class="col-sm-offset-2 col-sm-10">
<span class="text-danger small">{{ option.option_name.errors }}</span>
</div>
<label class="control-label col-sm-2">{{ option.option_name.label_tag }}</label>
<div class="col-sm-9">{{ option.option_name }}</div>
{% endfor %}
</div>
{% endfor %}
</form>
此外,在表单中还有一个“add_attribute_option”&#39;按钮(每个属性),&#39; add_attribute&#39;按钮,并提交&#39;按钮。
谢谢!
答案 0 :(得分:0)
Nicole Harris有这个很棒的教程,通过向我展示如何使用Formset解决了我的问题。谢谢妮可! http://whoisnicoleharris.com/2015/01/06/implementing-django-formsets.html