Categories
Python Answers

How to add CSS styling in Python Django forms?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *