CSS styling in Django forms

Taken from my answer to:
How to markup form fields with <div class=’field_type’> in Django

class MyForm(forms.Form):
    myfield = forms.CharField(widget=forms.TextInput(attrs={'class': 'myfieldclass'}))

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        self.fields['myfield'].widget.attrs.update({'class': 'myfieldclass'})

or

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'myfield': forms.TextInput(attrs={'class': 'myfieldclass'}),
        }

— EDIT —
The above is the easiest change to make to original question’s code that accomplishes what was asked. It also keeps you from repeating yourself if you reuse the form in other places; your classes or other attributes just work if you use the Django’s as_table/as_ul/as_p form methods. If you need full control for a completely custom rendering, this is clearly documented

— EDIT 2 —
Added a newer way to specify widget and attrs for a ModelForm.

Leave a Comment