I have a ChoiceField
in my Django Form:
我的Django表格中有一个ChoiceField:
sex = forms.ChoiceField(label='', choices=SEX)
I'd like to add a class
attr
to the field so I can style it. Something like the following usually works:
我想在场上添加一个类attr,这样我就可以设计它。像下面这样的东西通常有效:
forms.Field(label="Display name",help_text='',widget=forms.TextInput(attrs={'class': 'wideInput'}))
But this doesn't work for the ChoiceField, I get the following error:
但是这对ChoiceField不起作用,我得到以下错误:
TypeError: init() got an unexpected keyword argument 'attrs'
TypeError:init()得到一个意外的关键字参数'attrs'
What widget
should I use in order to add a class to my ChoiceField?
我应该使用哪个小部件来向ChoiceField添加类?
2 个解决方案
#1
39
I had a quick read of https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
我快速阅读了https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
which rabbited on about widgets - apparently they are
对小部件嗤之以鼻 - 显然他们是
Django’s representation of a HTML input element. The widget handles the rendering of the HTML
Django表示HTML输入元素。窗口小部件处理HTML的呈现
and then each form field is tied to a widget - have a read of:
然后每个表单字段绑定到一个小部件 - 阅读:
https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields
https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields
for the ChoiceField, the defaultWidget is "Select" (as noted in the above link). Ok, knowing the right widget, to add the class i just needed:
对于ChoiceField,defaultWidget是“Select”(如上面的链接所示)。好的,知道正确的小部件,添加我刚才需要的类:
widget=forms.Select(attrs={'class':'regDropDown'})
so that my final line ended up reading:
所以我的最后一行结束了:
sex = ChoiceField(label='', choices=SEX, widget=forms.Select(attrs={'class':'regDropDown'}))
Huzzah!
好哇!
#2
3
the ChoiceField use the forms.Select widget
ChoiceField使用forms.Select小部件
forms.Select(attrs={"name": "select_0","class": "form-control"})
#1
39
I had a quick read of https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
我快速阅读了https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
which rabbited on about widgets - apparently they are
对小部件嗤之以鼻 - 显然他们是
Django’s representation of a HTML input element. The widget handles the rendering of the HTML
Django表示HTML输入元素。窗口小部件处理HTML的呈现
and then each form field is tied to a widget - have a read of:
然后每个表单字段绑定到一个小部件 - 阅读:
https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields
https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields
for the ChoiceField, the defaultWidget is "Select" (as noted in the above link). Ok, knowing the right widget, to add the class i just needed:
对于ChoiceField,defaultWidget是“Select”(如上面的链接所示)。好的,知道正确的小部件,添加我刚才需要的类:
widget=forms.Select(attrs={'class':'regDropDown'})
so that my final line ended up reading:
所以我的最后一行结束了:
sex = ChoiceField(label='', choices=SEX, widget=forms.Select(attrs={'class':'regDropDown'}))
Huzzah!
好哇!
#2
3
the ChoiceField use the forms.Select widget
ChoiceField使用forms.Select小部件
forms.Select(attrs={"name": "select_0","class": "form-control"})