I'm trying to iterate over a MultipleSelect form that utilizes a CheckboxSelectMultiple widget and display each checkbox within. Here is the code for the iteration:
{% for choice in form.mp4_rasters %}
<label class="checkbox inline">
{{ choice }}
</label>
{% endfor %}
Here is the Form I declared:
from django import forms
MP4_CHOICES = ('240p', '360p', '720p', '1080p')
WEBM_CHOICES = MP4_CHOICES
OGG_CHOICES = MP4_CHOICES
MISC_CHOICES = ('MP3', 'Roku')
class BatchSubmitForm(forms.Form):
video_file = forms.FileField()
framerate = forms.FloatField()
title = forms.CharField()
destination = forms.CharField()
mp4_rasters = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=MP4_CHOICES)
webm_rasters = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=WEBM_CHOICES)
ogg_rasters = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=OGG_CHOICES)
misc_rasters = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=MISC_CHOICES)
When rendering, I would expect it to output each checkbox with the name I passed in, but instead of "240p", "360p", etc. I get numbers (4, 6, 2, 0) for each checkbox. I also tried rendering based on the widget's choices, using the following code, as an alternative:
{% for choice in form.mp4_rasters.field.widget.choices %}
<label class="checkbox inline">
{{ choice }}
</label>
{% endfor %}
That code renders the names appropriately, but then it doesn't include a checkbox. What can I add to either to make it render the checkboxes as well as the appropriate names as defined in the form?
Change:
MP4_CHOICES = ('240p', '360p', '720p', '1080p')
to
MP4_CHOICES = (('240p', '240p'),
('360p', '360p'),
('720p', '720p'),
('1080p', '1080p'))
The reason you are seeing the numbers is, choices
expects a tuple, and since you are not providing it a tuple, it is doing this.
('240p')
is being evaluated as ('2', '4', '0', 'p')
, and it is getting ('2', '4', '0', 'p')[1]
to display in the dropdown. Hence the (4, 6, 2, 0)
.