Categories
Python Answers

How to override widget in a Python Django ModelForm?

Spread the love

Sometimes, we want to override widget in a Python Django ModelForm.

In this article, we’ll look at how to override widget in a Python Django ModelForm.

How to override widget in a Python Django ModelForm?

To override widget in a Python Django ModelForm, we can set the widgets field to a dict with the field overrides.

For instance, we write

from django.forms import ModelForm, Textarea
from myapp.models import Author

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ('name', 'title', 'birth_date')
        widgets = {
            'name': Textarea(attrs={'cols': 80, 'rows': 20}),
        }

to create the AuthorForm model form class with a few fields.

We set the widgets field to a dict with the name field overridden with a Textarea with 80 columns and 20 rows.

Conclusion

To override widget in a Python Django ModelForm, we can set the widgets field to a dict with the field overrides.

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 *