Django form.MultipleChoiceField。自定义模板中的复选框

时间:2016-01-05 08:06:02

标签: django forms

我有这样的表格:

class PasswordForm(forms.Form):

    CHOICES=[('uppercase','Uppercase'),
            ('lowercase','Lowercase'),
            ('numbers','Numbers'),]

    password_length = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)],)
    options = forms.MultipleChoiceField(
                     widget=forms.CheckboxSelectMultiple, choices=CHOICES,)

如何在模板中自定义复选框字段?
我知道如何使用其他字段执行此操作,例如forms.Charfield()password_length,只需

<form action="" method="post">
    {{form.some_field}}
</form>

但它与我的MultipleChoiceField一起使用,我尝试了许多类似的事情 {{form.uppercase}}{{form.options.choices.uppercase}}并尝试{% for %}循环。
它只是没有返回,我没有通过浏览器检查器在html中看到它。

2 个答案:

答案 0 :(得分:2)

 <!-- With for-cycle: -->
{% for field in form %}
  {% for choice_id, choice_label in field.field.choices %}
    {{choice_id}}
    {{choice_label}}
  {% endfor %}
{% endfor %}

<!-- And my end version, where I edited only certain field. -->
{% for field in form %}
  {% if field.name == "your-field-name-here"%}
       <p><strong>{{field.name}}: </strong></p>
       {% for choice_id, choice_label in field.field.choices %}
                <input type="checkbox" name="category" value="{{choice_id}}" style="display:inline;">{{choice_label}}
      {% endfor %}
   {% else %}
       <p>{{ field.errors }}<label style="display:table-cell;">{{field.name}}: </label>{{ field }}</p>
   {% endif %}
{% endfor %}

<!-- If you want to edit all fields with options: {% if field.choices %} -->

答案 1 :(得分:1)

您应该将这些选项写为以下形式的字段:

class PasswordForm(forms.Form):
    uppercase = forms.CharField(widget=forms.CheckboxInput())
    lowercase = forms.CharField(widget=forms.CheckboxInput())
    numbers = forms.CharField(widget=forms.CheckboxInput())
    password_length = forms.ChoiceField(choices=[(x, x) for x in range(1, 32)],)

然后将表单呈现为模板,并在模板中:

{{ form.uppercase }}

将显示

<input name="uppercase" type="checkbox">