【发布时间】:2018-10-20 14:10:19
【问题描述】:
我想为 django ChoiceField 中的<option/> 标签定义一个class 属性,我该怎么做?
我尝试设置小部件类,并在 forms.py 中指定这样的属性:
field = forms.ChoiceField(choices=[(1, 'foo'), (2, 'bar')], widget=forms.Select(attrs={'class': 'form-control'}))
在我的template.html 中渲染如下:
{{ form.field }}
输出是:
<select name="field" class="form-control" id="id_field">
<option value="1">foo</option>
<option value="2">bar</option>
</select>
而我想要的是这样的:
<select name="field" class="form-control" id="id_fields">
<option class="form-control" value="1">foo</option>
<option class="form-control" value="2">bar</option>
</select>
最简单的方法是什么?
【问题讨论】:
-
显然不是很有帮助,但最后一分钟你可以使用 JS ;)
-
@J.C.Rocamonde 我知道,但我想知道在 Django 中是否有办法做到这一点......
标签: django python-3.x django-forms django-2.1