我在表单中有一个选择字段,现在我需要迭代该字段中的选项。
{{ 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>
现在我需要为选项添加一些属性,因此我需要的是:
<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
但它什么也没给出
最佳答案
今天我一直在努力解决这个问题并找到了解决方案。是的,您可以直接在模板中迭代 select 标签的选项。以下是在模板中执行此操作的方法:
<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
字段,其选项设置如下:
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()]
关于django - 如何迭代模板中 SelectField 的选项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9221010/