迭代CheckboxSelectMultiple中的选项 [英] Iterate over choices in CheckboxSelectMultiple

查看:150
本文介绍了迭代CheckboxSelectMultiple中的选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个CheckboxSelectMultiple字段,为什么我不能迭代单个选择?

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

这不起作用:

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

即使指定 {{choice.0}} ,我该怎么做?

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

谢谢

推荐答案

模板,行为字段,实际上是一个 BoundField 的实例(这是一个绑定字段和它的渲染值)。这意味着属性有些不同。

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.

要作为元组迭代选择:

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

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

要遍历元素选择元组:

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

Produces: 1 = One
          2 = Two

希望有所帮助。话虽如此,但我不知道你需要做什么的背景;在表面上看起来似乎并不像django一样。您可能会发现,使用自定义表单字段或自定义模板标签可以提供更便于携带的可重用的实现,可以更好地维护django在视图代码和模板代码之间的预期分隔。当然,YMMV可能是直接迭代方法在这种情况下适合你。

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.

这篇关于迭代CheckboxSelectMultiple中的选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆