2012-07-12 43 views
20

我有一个ChoiceField在我的Django表单:如何在Django的ChoiceField中添加一个“类”?

sex = forms.ChoiceField(label='', choices=SEX) 

我想一个classattr添加到现场,所以我可以样式。像下面的内容通常工作:

forms.Field(label="Display name",help_text='',widget=forms.TextInput(attrs={'class': 'wideInput'})) 

但是,这并不为ChoiceField工作,我得到以下错误:

TypeError: init() got an unexpected keyword argument 'attrs'

我应该按顺序使用什么widget一类添加到我的ChoiceField?

回答

38

我有https://docs.djangoproject.com/en/1.4/ref/forms/widgets/

快速阅读这rabbited关于部件 - 显然他们是

Django’s representation of a HTML input element. The widget handles the rendering of the HTML

,然后每个表单字段被绑定到一个部件 - 有一个读:

https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields

对于ChoiceField,defaultWidget是“Select”(如上面链接中所述)。好了,知道正确的窗口小部件,添加类我只需要:

widget=forms.Select(attrs={'class':'regDropDown'}) 

,使我的最后一行结束了阅读:

sex = ChoiceField(label='', choices=SEX, widget=forms.Select(attrs={'class':'regDropDown'})) 

好哇!

+0

你应该能够在一定时间后,接受你自己的答案 – 2012-07-12 09:00:19

+0

感谢这个 – ajt 2012-10-08 12:06:20

3

的ChoiceField使用forms.Select部件

forms.Select(attrs={"name": "select_0","class": "form-control"}) 
相关问题