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

Gor*_*ran 27 django django-templates django-forms

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

{{ 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>
Run Code Online (Sandbox Code Playgroud)

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

<select name="myselect" id="id_myselect">
{% for x in form.myselect %}
    <option value="{{ x.id }}">{{ x.name }}</option>
{% endfor %}
</select>
Run Code Online (Sandbox Code Playgroud)

但是有一个错误:

Caught TypeError while rendering: 'BoundField' object is not iterable
Run Code Online (Sandbox Code Playgroud)

我试过form.myselect.all,form.myselect.option_set但它没有给出任何东西

小智 73

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

在这种情况下,我在表单中有一个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()]
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 我遇到了同样的问题并且在没有改变任何其他东西的情况下取得了成功,但添加了:`{% for c in form.fields.customer.queryset %}&lt;option value="{{ c.id }}"&gt;{{ c.name| capfirst }}&lt;/option&gt;{% endfor %}` (2认同)

epy*_*nkn 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>
Run Code Online (Sandbox Code Playgroud)

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

    {% load widget_tweaks %}
    {{ form.myselect|add_class:"i-can-haz-custom-classes-easily" }}
Run Code Online (Sandbox Code Playgroud)

使用django-widget-tweaks进行操作也会为你设置默认的'selected ='选择"',这太棒了!


Cíc*_*ves 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>
Run Code Online (Sandbox Code Playgroud)