如何添加“班级”到Django中的ChoiceField? [英] How do I add a "class" to a ChoiceField in Django?

查看:112
本文介绍了如何添加“班级”到Django中的ChoiceField?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Django表单中有一个 ChoiceField

I have a ChoiceField in my Django Form:

gender = forms.ChoiceField(label='', choices=GENDER)

我想添加一个 class attr 到字段,这样我就可以设置样式。像下面这样的东西通常可以工作:

I'd like to add a class attr to the field so I can style it. Something like the following usually works:

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

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

But this doesn't work for the ChoiceField, I get the following error:


TypeError: init ()有一个意外的关键字参数'attrs'

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

我应该使用什么 widget 来添加类

What widget should I use in order to add a class to my ChoiceField?

推荐答案

我快速阅读了 https://docs.djangoproject.com/en/1.4/ref/forms/widgets/

涉及到小部件-显然,它们是

which rabbited on about widgets - apparently they are


Django对HTML输入元素的表示。小部件处理HTML的呈现

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

然后将每个表单字段绑定到小部件-阅读以下内容:

and then each form field is tied to a widget - have a read of:

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

对于ChoiceField, defaultWidget是选择(如上面的链接所述)。确定,知道正确的小部件,添加我刚需要的类:

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:

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

,以便最后一行显示为:

so that my final line ended up reading:

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

Huzzah!

这篇关于如何添加“班级”到Django中的ChoiceField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆