我创建了一个有2个单选按钮(男/女)的表单。下面会有一个名字和姓氏的输入框。如果我使用formset来复制表单,它将包含每个输入框的单选按钮,我想排除它。假设一旦用户选择"男性"名称应与其性别选择相匹配。
输出应如下所示:
男性O女性
名字:_______________姓氏:_______________
名字:_______________姓氏:_______________
...
forms.py
from django import forms
class NameForm (forms.Form):
GENDER = (
('Male', 'Male'),
('Female', 'Female')
)
gender = forms.ChoiceField (widget = forms.RadioSelect, choices = GENDER)
first_name = forms.CharField (max_length = 20)
last_name = forms.CharField (max_length = 20)
Shell Output:
>>> from django.forms.formsets import formset_factory
>>> from nameform.forms import NameForm
>>>
>>> NameFormSet = formset_factory (NameForm, extra = 2)
>>> formset = NameFormSet ()
>>> for form in formset:
... print (form.as_table())
...
<tr><th><label for="id_form-0-gender_0">Gender:</label></th><td><ul id="id_form-0-gender">
<li><label for="id_form-0-gender_0"><input id="id_form-0-gender_0" name="form-0-gender" type="radio" value="Male" /> Male</label></li>
<li><label for="id_form-0-gender_1"><input id="id_form-0-gender_1" name="form-0-gender" type="radio" value="Female" /> Female</label></li>
</ul></td></tr>
<tr><th><label for="id_form-0-first_name">First name:</label></th><td><input id="id_form-0-first_name" maxlength="20" name="form-0-first_name" type="text" /></td></tr>
<tr><th><label for="id_form-0-last_name">Last name:</label></th><td><input id="id_form-0-last_name" maxlength="20" name="form-0-last_name" type="text" /></td></tr>
<tr><th><label for="id_form-1-gender_0">Gender:</label></th><td><ul id="id_form-1-gender">
<li><label for="id_form-1-gender_0"><input id="id_form-1-gender_0" name="form-1-gender" type="radio" value="Male" /> Male</label></li>
<li><label for="id_form-1-gender_1"><input id="id_form-1-gender_1" name="form-1-gender" type="radio" value="Female" /> Female</label></li>
</ul></td></tr>
<tr><th><label for="id_form-1-first_name">First name:</label></th><td><input id="id_form-1-first_name" maxlength="20" name="form-1-first_name" type="text" /></td></tr>
<tr><th><label for="id_form-1-last_name">Last name:</label></th><td><input id="id_form-1-last_name" maxlength="20" name="form-1-last_name" type="text" /></td></tr>
答案 0 :(得分:0)
您需要表单和表单集。表单只包含名称,包含重复元素的formset。
使用重复的表单类没有意义,然后破解它以不同方式处理第一个。
或者,如果这是一个数据问题(比如传统界面),并且表单需要包含两个..那么您可能隐藏所有其他元素并使用javascript填写隐藏的性别选择。
但实际上,您应该使用Form
和FormSet
。
{{ form.as_p }}
{% for form in formset %}
{{ form.as_p }}
{% endfor %}