Subclass a Django Model Form and Add Extra Fields

A common use case of forms is to subclass some type of base form and add a couple extra fields. Take the following base form for example:

from django import forms
from app.models import User
from app.forms.widgets import *
class RegisterBaseForm(forms.ModelForm):
username = forms.CharField(max_length=User._meta.get_field('username').max_length)
email = forms.CharField(max_length=User._meta.get_field('email').max_length, widget=HTML5EmailInput())
password = forms.CharField(min_length=6, max_length=16, widget=forms.PasswordInput())
class Meta:
model = User
fields = ('username', 'email', 'password')

view raw
forms.py
hosted with ❤ by GitHub

The model has a variety of other fields in it so I’m using fields in the Meta class to limit to just these three. Now let’s add a couple fields in a subclass:

from django import forms
from base import *
from app.models import User
class RegisterEmailForm(RegisterBaseForm):
first_name = forms.CharField(max_length=User._meta.get_field('first_name').max_length)
last_name = forms.CharField(max_length=User._meta.get_field('last_name').max_length)
class Meta(RegisterBaseForm.Meta):
fields = RegisterBaseForm.Meta.fields + ('first_name', 'last_name')

view raw
forms.py
hosted with ❤ by GitHub

As you can see, rather than re-specifying all the fields in the Meta class I am simply adding the new fields to the parent’s existing field list.

5 thoughts on “Subclass a Django Model Form and Add Extra Fields”

  1. i tried this code so that in my profile form i have some user fields but the problem is the changes on the user’s fields are not saved

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s