Django表单-更改小部件属性
我想为djangoDjango表单-更改小部件属性,django,python-3.x,django-forms,django-2.1,Django,Python 3.x,Django Forms,Django 2.1,我想为djangoChoiceField中的标记定义一个class属性,我该怎么做 我试图设置widget类,并在forms.py中指定这样的属性: field = forms.ChoiceField(choices=[(1, 'foo'), (2, 'bar')], widget=forms.Select(attrs={'class': 'form-control'})) 并在我的template.html中呈现如下: {{form.field} 输出为: <select name="
ChoiceField
中的
标记定义一个class
属性,我该怎么做
我试图设置widget类,并在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>
福
酒吧
最简单的方法是什么?您可以创建一个并编写一个自定义模板字段。如果要重用属性,这是最好的选择
该应用程序应包含一个templatetags目录,与models.py、views.py等处于同一级别。如果该目录不存在,请创建它-不要忘记\uuuuu init\uuuuuuuuuuuuuuuuuupy文件,以确保该目录被视为Python包
在应用程序文件夹中创建此结构
内部过滤器.py
from django import template
register = template.Library()
@register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
在
{%block content%}
之前,将{%load filters%}
添加到template.html
这就是应用过滤器的方式:
{{form.field|addclass:'form-control'}}
现在,您应该忘记在forms.py中向HTML元素添加类
from django import template
register = template.Library()
@register.filter(name='addclass')
def addclass(value, arg):
return value.as_widget(attrs={'class': arg})
如果您不喜欢模板标记方式,或者只是在寻找低成本的临时解决方案,那么您应该查看此链接
实现这一点的最简单方法是将
选择小部件子类化,并将选项\u inherits\u attrs
设置为True:
class CustomSelect(forms.Select):
option_inherits_attrs = True
然后在创建表单时使用自定义小部件:
class TestForm(forms.Form):
items = forms.ChoiceField(
choices=[(1, 'foo'), (2, 'bar')],
widget=CustomSelect(
attrs={'class': 'form-control'}
)
显然不是很有帮助,但最后一分钟您可以使用JS;)@J.C.Rocamonde我知道,但我想知道在Django中是否有这样做的方法……我可以使用模板标记方法,但它仍然没有将类属性应用于子
元素,只应用于父
,这与为Widgetwo指定属性相同,就是这么简单!谢谢