Reputation: 41
I have a template which goes through a queryset and creates a checkbox for each item which seems to be a validation problem. I can only submit this when I check every checkbox and I just can't seem to figure out what is wrong.
my template:
<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>
my forms.py
class AddSectionForm(forms.Form):
sections = forms.MultipleChoiceField(
required=False, widget=forms.CheckboxSelectMultiple())
Urghh, I'm an idiot, it's the required=""
in the html checkbox object!
Upvotes: 1
Views: 432
Reputation: 476649
Your checkboxes should not have required=""
, otherwise it is required to check these. Furthermore it is probably more elegant to use a ModelMultipleChoiceField
:
class AddSectionForm(forms.Form):
sections = forms.ModelMultipleChoiceField(
queryset=Section.objects.all(),
required=True,
widget=forms.CheckboxSelectMultiple()
)
Upvotes: 0
Reputation: 41
Thanks Willem, you got it! Also needed to change the checkbox values for the primary keys.
forms.py:
class AddSectionForm(forms.Form):
sections = forms.MultipleChoiceField(
required=True, widget=forms.CheckboxSelectMultiple(),
choices=Section.objects.all().values_list())
template:
<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>
Upvotes: 1