Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a "class" to a ChoiceField in Django?

Tags:

django

I have a ChoiceField in my Django Form:

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

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'})) 

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

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

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

like image 637
bharal Avatar asked Jul 12 '12 00:07

bharal


People also ask

How do you make a field not required in Django?

The simplest way is by using the field option blank=True (docs.djangoproject.com/en/dev/ref/models/fields/#blank).


2 Answers

I had a quick read of 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

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

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!

like image 80
bharal Avatar answered Sep 21 '22 23:09

bharal


the ChoiceField use the forms.Select widget

forms.Select(attrs={"name": "select_0","class": "form-control"}) 
like image 31
jmunoz Avatar answered Sep 21 '22 23:09

jmunoz