【问题标题】:Django form.MultipleChoiceField . Customize checkboxes in templateDjango form.MultipleChoiceField 。自定义模板中的复选框
【发布时间】:2016-04-08 23:47:41
【问题描述】:

我有这个表格:

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 中看到它。

【问题讨论】:

  • doent works 需要什么?错误?结果无效?您正在尝试做什么但目前没有发生?

标签: django forms


【解决方案1】:

 <!-- 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 %} -->

【讨论】:

    【解决方案2】:

    您应该将这些选项写为表单的字段:

    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">
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-17
      • 2023-03-23
      • 1970-01-01
      • 2019-04-03
      • 2016-12-04
      • 1970-01-01
      相关资源
      最近更新 更多