我的 Django 表单中有一个 ChoiceField
:
gender = forms.ChoiceField(label='', choices=GENDER)
我想向该字段添加一个 class
attr
以便我可以设置其样式。类似以下内容通常有效:
forms.Field(label="Display name",help_text='',widget=forms.TextInput(attrs={'class': 'wideInput'}))
但这不适用于 ChoiceField,我收到以下错误:
TypeError: init() got an unexpected keyword argument 'attrs'
我应该使用什么小部件
才能将类添加到我的 ChoiceField?
最佳答案
我快速阅读了 https://docs.djangoproject.com/en/1.4/ref/forms/widgets/
其中对小部件的关注 - 显然它们是
Django’s representation of a HTML input element. The widget handles the rendering of the HTML
然后每个表单字段都绑定(bind)到一个小部件 - 请阅读:
https://docs.djangoproject.com/en/1.4/ref/forms/fields/#built-in-fields
对于 ChoiceField,defaultWidget 是“Select”(如上面的链接所述)。好的,知道正确的小部件,添加我只需要的类:
widget=forms.Select(attrs={'class':'regDropDown'})
这样我的最后一行就变成了:
gender = ChoiceField(label='', choices=SEX, widget=forms.Select(attrs={'class':'regDropDown'}))
万岁!
关于django - 如何将 "class"添加到 Django 中的 ChoiceField?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11443658/