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

查看:21
本文介绍了迭代 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?

谢谢

推荐答案

在模板内部,travels 字段实际上是 BoundField(它是一个 Django 对象)的一个实例将字段及其渲染值绑定在一起).这意味着属性有些不同.

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') -

分别迭代选择元组中的元素:

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

希望有所帮助.话虽如此,但我不确定您需要这样做的上下文.从表面上看,它似乎不太像 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天全站免登陆