如何迭代模板中 SelectField 的选项? [英] How do I iterate over the options of a SelectField in a template?

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

问题描述

我在表单中有一个选择字段,现在我需要遍历该字段中的选项.

I have a select field in the form and now I need to iterate over options in this field.

{{ form.myselect }} 给我这个:

<select name="myselect" id="id_myselect">
    <option value="" selected="selected">---------</option>
    <option value="2">Item 1</option>
    <option value="3">Item 2</option>
    ...
</select>

现在我需要向选项添加一些属性,因此我需要的是:

Now I need to add some attributes to the options and because of that what I need is:

<select name="myselect" id="id_myselect">
{% for x in form.myselect %}
    <option value="{{ x.id }}">{{ x.name }}</option>
{% endfor %}
</select>

但是有一个错误:

Caught TypeError while rendering: 'BoundField' object is not iterable

我试过 form.myselect.all, form.myselect.option_set 但它什么也没给

I tried form.myselect.all, form.myselect.option_set but it gives nothing

推荐答案

我今天一直在努力解决这个问题,并找到了解决方案.是的,您可以直接在模板中迭代 select 标签的选项.以下是在模板中执行此操作的方法:

I've been struggling with this problem today and found the solution. Yes, you can iterate over options of the select tag directly in template. Here's how to do it in template:

<select id="id_customer" name="customer">
{% for x, y in form.fields.customer.choices %}
    <option value="{{ x }}"{% if form.fields.customer.value == x %} selected{% endif %}>{{ y }}</option>
{% endfor %}
</select>

在这种情况下,我在表单中有一个 customer 字段,其中的选项设置如下:

In this case I have a customer field in the form which has choices set up as follows:

class SomeForm(forms.Form):
    customer = forms.ChoiceField(label=u'Customer')

    def __init__(self, *args, **kwargs):
        super(SomeForm, self).__init__(*args, **kwargs)
        self.fields['customer'].choices = [(e.id, e.customer) for e in Customers.objects.all()]

希望能帮到你

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

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