【问题标题】:Multiple checkboxes validation rules, only works when every checkbox selected多个复选框验证规则,仅在选中每个复选框时有效
【发布时间】:2022-02-02 02:53:33
【问题描述】:

我有一个模板,它通过一个查询集并为每个项目创建一个复选框,这似乎是一个验证问题。我只能在检查每个复选框时才提交此文件,但我似乎无法弄清楚出了什么问题。

我的模板:

<form method="POST">
   {% csrf_token %}
   <fieldset>
      {% for choice in choices %}
      {{ choice.description }}
      <input type="checkbox" value="{{choice.section}}" name="sections" required="">
      {% endfor %}
      <button type="submit">Submit</button>
   </fieldset>
</form>

我的表单.py

class AddSectionForm(forms.Form):
    sections = forms.MultipleChoiceField(
        required=False, widget=forms.CheckboxSelectMultiple())

编辑

呃,我是个白痴,这是 html 复选框对象中的required=""

【问题讨论】:

  • 请将解决方案作为答案发布在下面,而不是编辑您的问题。
  • 原来这只是部分答案,我通过验证解决了问题,但这仍然无法通过 form.is_valid()
  • @Chonker: 你的sections没有choices=......
  • 能发下相关观点吗?

标签: django validation checkbox


【解决方案1】:

谢谢威廉,你明白了!还需要更改主键的复选框值。

forms.py:

class AddSectionForm(forms.Form):
sections = forms.MultipleChoiceField(
    required=True, widget=forms.CheckboxSelectMultiple(),
    choices=Section.objects.all().values_list())

模板:

<form method="POST">
{% csrf_token %}
<fieldset>
{% for choice in choices %}
{{ choice.description }}
<input type="checkbox" value="{{choice.pk}}" name="sections">
{% endfor %}
<button type="submit">Submit</button>
</fieldset>

【讨论】:

    【解决方案2】:

    你的复选框不应该有required="",否则需要勾选这些。此外,使用ModelMultipleChoiceField 可能更优雅:

    class AddSectionForm(forms.Form):
        sections = forms.ModelMultipleChoiceField(
            queryset=Section.objects.all(),
            required=True,
            widget=forms.CheckboxSelectMultiple()
        )

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-29
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 2012-01-06
      相关资源
      最近更新 更多