Add class to form field Django ModelForm

If you can’t use a third-party app and want to add a class (e.g., “form-control”) to every field in a form in a DRY manner, you can do so in the form class __init__() method like so:

class ExampleForm(forms.Form):
    # Your declared form fields here
    ...

    def __init__(self, *args, **kwargs):
        super(ExampleForm, self).__init__(*args, **kwargs)
        for visible in self.visible_fields():
            visible.field.widget.attrs['class'] = 'form-control'

You might need to handle checking for existing classes in attrs too, if for some reason you’ll be adding classes both declaratively and within __init__(). The above code doesn’t account for that case.

Worth mentioning:

You specified that you don’t want to use third-party packages. However, I’ll take one second to mention that one of the simplest ways of automatically making forms render in the style of Bootstrap is to use django-crispy-forms, like this:

# settings.py
CRISPY_TEMPLATE_PACK = 'bootstrap3'

# forms.py
from crispy_forms.helper import FormHelper
class ExampleForm(forms.Form):
    # Your declared form fields here
    ...
    helper = FormHelper()

# In your template, this renders the form Bootstrap-style:
{% load crispy_forms_tags %}
{% crispy form %}

Leave a Comment