Adding Classes to Django Forms
When building forms in Django, adding CSS classes is essential to style your forms with frameworks like Bootstrap or custom CSS. Django provides several ways to add classes to form fields — both for regular forms.Form and ModelForm.
Why Add Classes?
- Integrate with CSS frameworks (e.g.,
form-controlin Bootstrap). - Customize the appearance of individual fields.
- Handle form layout dynamically using frontend tools.
Method 1: Manually Adding Classes in __init__()
You can override the form’s __init__ method to update each field's widget attributes.
from django import forms
class ContactForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for visible in self.visible_fields():
visible.field.widget.attrs['class'] = 'form-control'
You can also target specific fields:
self.fields['name'].widget.attrs.update({
'class': 'form-control',
'placeholder': 'Your full name'
})
Adding Classes in a ModelForm
ModelForms work exactly the same way, since they inherit from forms.ModelForm.
from django import forms
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['title', 'price', 'description']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs.update({'class': 'form-control'})
Tip: Setting Classes in the widgets Dictionary (Meta class)
A more declarative and concise way (but less flexible) is to define classes in the widgets dictionary of the Meta class.
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['title', 'price']
widgets = {
'title': forms.TextInput(attrs={'class': 'form-control'}),
'price': forms.NumberInput(attrs={'class': 'form-control'}),
}
Use this method if you don’t need dynamic class logic.
Recap
| Method | Flexibility | Use case |
|---|---|---|
__init__() override |
High | When adding logic dynamically |
Meta.widgets dictionary |
Medium | For declarative forms |
Best Practice
If you're working with Bootstrap or any CSS framework, make sure all your input fields have form-control or equivalent class, or else the form layout might break.
To make this easier across your whole app, consider writing a mixin or using packages like django-crispy-forms.
Want to try out our tools? Visit the Django Tools Hub to explore utilities like the Django Forms Generator.