表单中有一个select字段,现在我需要迭代该字段中的选项.

{{ 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相关问答推荐

Django Signals:从实例访问ManyToManyRel值

自定义公钥打破Django管理内联逻辑

如何根据递归ManyToManyField值创建Django查询集?

Django-无法显示基于字段值的元素

在Django管理中仅显示外键的特定值

Django OneToOneFieldto抽象对象

我如何告诉Django如何恢复自定义迁移?

APIView查询未返回任何结果

通过在其他查询中使用来过滤对象

如何创建复杂的查询?| ChartJS 和 Django

将两个视图重定向到具有不同 url id Django 的一个模板的正确方法

在Django测试get方法中获取HttpResponseNotFound

如何计算 Django 模型中特定对象的数量?

"" 需要有字段 "id" 的值才能使用这种多对多关系

在 GoDaddy 上安装 django 站点

如何访问 Django Rest Framework 上的自定义 HTTP 请求标头?

Django ModelChoiceField optgroup 标签

使用 Django 1.5 实现多种用户类型

如何找到两个 Django 查询集的交集?

Django中'related_name'和'related_query_name'属性之间的区别?