如何在模板中迭代SelectField的选项?

时间:2012-02-10 00:20:36

标签: django django-forms django-templates

我在表单中有一个选择字段,现在我需要在此字段中迭代选项。

{{ 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.allform.myselect.option_set但它没有提供任何内容

4 个答案:

答案 0 :(得分:70)

我今天一直在努力解决这个问题,并找到了解决方案。是的,您可以直接在模板中迭代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 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()]

希望这有帮助

答案 1 :(得分:23)

可以使用:

    <select name="myselect" class="i-can-add-my-own-attrs-now" id="id_myselect">
        {% for id, name in form.myselect.field.choices %}
        <option value="{{ id }}">{{ name }}</option>
        {% endfor %}
    </select>

但真的,更好的方法是使用django-widget-tweaks

    {% load widget_tweaks %}
    {{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}

用django-widget-tweaks做这件事也会为你设置默认的'selected ='选择“',这太棒了!

答案 2 :(得分:7)

我这样做:

<select id="id_construction_type" name="construction_type" class="form-control input-md">
{% for value, key in form_urban.fields.construction_type.choices %}
    <option value="{{ value }}"{% if form_urban.initial.construction_type == value %} selected {% endif %}>
        {{ key }}
    </option>
{% endfor %}
</select>

答案 3 :(得分:0)

使用模板中的单选按钮。

    <table>
        {% for x,y in form.fields.Customer.choices %}
        <tr>
            <td><input id="id_Customer_{{x}}" {% if form.fields.Customer.value == x %}checked="checked"{% endif %} name="Customer" type="radio" value="{{x}}" /></td>
            <td>{{ y }}</td>
        </tr>
        {% endfor %}
    </table>
相关问题