Menu
×
Γ—
   ❮   
PYTHON FOR DJANGO DJANGO FOR BEGINNERS DJANGO SPECIFICS PAYMENT INTEGRATION API BASICS NUMPY FOR ML Roadmap
     β―   

DJANGO FORMS

Adding classes to form fields

×

Share this Topic

Share Via:

Thank you for sharing!


🎨 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-control in 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.


References


Django-tutorial.dev is dedicated to providing beginner-friendly tutorials on Django development. Examples are simplified to enhance readability and ease of learning. Tutorials, references, and examples are continuously reviewed to ensure accuracy, but we cannot guarantee complete correctness of all content. By using Django-tutorial.dev, you agree to have read and accepted our terms of use , cookie policy and privacy policy.

Β© 2025 Django-tutorial.dev .All Rights Reserved.
Django-tutorial.dev is styled using Bootstrap 5.
And W3.CSS.