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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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') |
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.
It’s not working anymore (Django 1.11)
I have this code running on Django 1.11 without issue. What error are you seeing?
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
brilliance! this is working as expected in v2.1! Thank you!
Brilliance! this is working as expected in v2.1! Thank you!