Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

django - Iterate over choices in CheckboxSelectMultiple

I have a CheckboxSelectMultiple field, why can't I iterate over the single choices?

This doesn't work:

  {%for choice in form.travels.choices%}
    {{choice}}
  {%endfor%}

Even specifying {{choice.0}} doesn't help, how could i do this?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Inside the template, the travels field as actually an instance of BoundField (which is a Django object that binds together the field and its value for rendering). This means the properties are somewhat different.

To iterate over the choices as a tuple:

{% for choice in form.travels.field.choices %}
    {{ choice }} - 
{% endfor %}

Produces: (1, 'One') - (2, 'Two') -

To iterate over the elements in the choice tuples separately:

{% for choice_id, choice_label in form.travels.field.choices %}
    {{ choice_id }} = {{ choice_label }} <br/>
{% endfor %}

Produces: 1 = One
          2 = Two

Hope that helps. Having said that, though, I'm not sure of the context in which you're needing to do this; on the surface, it doesn't seem very django-like. You may find that using a custom form field or a custom template tag gives you a more portable, re-usable implementation that better maintains django's intended separation between view code and template code. Of course, YMMV and it could well be that the direct iteration approach is appropriate for you in this case.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...