Menu Close

How to add CSS styling in Python Django forms?

To add CSS styling in Python Django forms, we can call attrs.update.

For instance, we write

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

to call attrs.update with a dict with the class key set to the class with the styles we want to apply on the myfield field.

Posted in Python, Python Answers