如何迭代模板中SelectField的选项? [英] How do I iterate over the options of a SelectField in a template?
本文介绍了如何迭代模板中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>
现在我需要为选项添加一些属性,因为我需要的是: p>
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'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>
在这种情况下,我有一个客户字段的形式,其选择设置如下: p>
In this case I have a Customer field in the form which has choices set up as follows:
class Some_Form(forms.Form):
Customer = forms.ChoiceField(label=u'Customer')
def __init__(self, *args, **kwargs):
super(Some_Form, self).__init__(*args, **kwargs)
self.fields['Customer'].choices = [(e.id, e.Customer) for e in Customers.objects.all()]
希望这有助于
这篇关于如何迭代模板中SelectField的选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文