Django迭代CheckboxSelectMultiple呈现数字

时间:2013-10-11 20:38:46

标签: django forms django-forms widget django-widget

我正在尝试迭代使用CheckboxSelectMultiple小部件的MultiSelect表单并显示其中的每个复选框。以下是迭代的代码:

{% for choice in form.mp4_rasters %}
       <label class="checkbox inline">
          {{ choice }}
       </label>
{% endfor %}

以下是我声明的表格:

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)

渲染时,我希望它输出每个复选框的名称我传入,但不是“240p”,“360p”等。我得到每个复选框的数字(4,6,2,0)。我还尝试使用以下代码基于窗口小部件的选择进行渲染:

{% for choice in form.mp4_rasters.field.widget.choices %}
           <label class="checkbox inline">
              {{ choice }}
           </label>
    {% endfor %}

该代码适当地呈现名称,但它不包含复选框。我可以添加什么来使其呈现复选框以及表单中定义的相应名称?

1 个答案:

答案 0 :(得分:1)

变化:

MP4_CHOICES = ('240p', '360p', '720p', '1080p')

MP4_CHOICES = (('240p', '240p'), 
               ('360p', '360p'), 
               ('720p', '720p'), 
               ('1080p', '1080p'))

你看到数字的原因是,choices期望一个元组,并且因为你没有提供元组,所以它正在这样做。

('240p')正在评估为('2', '4', '0', 'p'),并且在下拉列表中显示('2', '4', '0', 'p')[1]。因此(4, 6, 2, 0)