开发者

django problem iterating over SelectMultiple/CheckboxSelectMultiple in template

I'm having a real hard time with this problem because I found the answer but it doesn't work. I have a Django app with a form with a SelectMultiple/CheckboxSelectMultiple field...

My Aim

I need to iterate in the template over the options of my "labels" field.

Printing {{ form.labels }} in the template works fine (that is, that object gets there OK).

My Problem

All over the web I found the same way to do this - and I tried all variations I could think of. For exampl see @Jarret Hardie 's answer here.

My Code

models.py

class myModle(models.Model):
  labels = models.CharField(max_length=1000)
  class Meta:
    db_table = u'myTable'

forms.py

class MYMODELForm(ModelForm):
    class Meta:
        model = myModel
    def __init__(self, *args, **kwargs):
        super(MYMODELForm, self).__init__(*args, **kwargs)
    labelList = set()
    #now I'm filling the set with strings (label names)
    #one of the two following line:
    self.fields['labels'] = for开发者_如何学JAVAms.CharField(required=False,widget=forms.CheckboxSelectMultiple(choices=[(x,x) for x in labelList]))
    self.fields['labels'] = forms.CharField(required=False,widget=forms.SelectMultiple(choices=[(x,x) for x in labelList]))

myTemplate.html

<table>
    <tr>
         <td>
            <!-- All variations of... -->
            {% for choice_id, choice_label in form.labels.field.items %} 
            {{ choice_id }} = {{ choice_label }} <br/>
            {% endfor %} 
         </td>
     </tr>
 </table>       

myStyle.css

Nothing interesting her...

views.py

Nothing interesting her...

So...

Why oh why is this not working???


You're using items instead of choices.

Current:

{% for choice_id, choice_label in form.labels.field.items %}

Should be:

{% for choice_id, choice_label in form.labels.field.choices %}

since you've put the choices on the widget, those choices override the field's choices, so iterate over the widget choices:

{% for choice_id, choice_label in form.labels.field.widget.choices %}

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜