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

标签 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 但它什么也没给出

最佳答案

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

相关文章:

django - 模板中的Django多对多

python - Django/Python 世界中是否有与 WordPress 的 SimplePie 插件等效的东西?

python - 我的 Django if 语句无法正常工作

python - 405 客户端错误 : Method Not Allowed for url: https://rinkeby. infura.io

django - 如何记住 QuerySet.update() 之后要处理的对象

python - 在用户表单 django 中设置默认值

python - 可以在 Django {% ifequal %} 表达式中使用带有查找的变量吗?

sql - 从大表中获取每个 parent 的最新 child - 查询太慢

python - django 模型表单自定义字段

python - 使用 ModelMultipleChoiceField 保存时出现 ValueError