You are going to need this in case you want to allow users creating an account to input more than just their username and password.

Import everything you need:

from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User

And your class that uses the UserCreationForm class (still in

class RegisterForm(UserCreationForm):
    # declare the fields you will show
    username = forms.CharField(label="Your Username")
    # first password field
    password1 = forms.CharField(label="Your Password")
    # confirm password field
    password2 = forms.CharField(label="Repeat Your Password")
    email = forms.EmailField(label = "Email Address")
    first_name = forms.CharField(label = "Name")
    last_name = forms.CharField(label = "Surname")

    # this sets the order of the fields
    class Meta:
        model = User
        fields = ("first_name", "last_name", "email", "username", "password1", "password2", )

    # this redefines the save function to include the fields you added
    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False) = self.cleaned_data["email"]
        user.first_name = self.cleaned_data["first_name"]
        user.last_name = self.cleaned_data["last_name"]

    if commit:
        return user

6 thoughts on “Django: extend UserCreationForm

    • To display the registration form you should have this in your

      def register(request):
      	if request.method == 'POST':
      		form = RegisterForm(request.POST)
      		if form.is_valid():
      			new_user =
      		return HttpResponseRedirect("./")
      		form = RegisterForm()
      	return render(request, 'template/register.html', { 'form': form })

      Hope it helps!

  1. Thanks for the example. . .One question, since you’re inheriting from UserCreationForm, do you really need to add in the password fields explicitly? They’re already in your subclassed form since you’re inheriting from the base class (UserCreationForm).

    When I’ve subclassed UserCreationForm, I just add in the new parts I need such as an email, then override the save method, making sure to include the email in this. The password stuff is already done for you. . .Or am I missing something?

    class MyRegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)

    class Meta:
    model = User
    fields = (‘username’, ’email’, ‘password1’, ‘password2’)

    def save(self, commit=True):
    user = super(MyRegistrationForm, self).save(commit=False) = self.cleaned_data[“email”]
    if commit:
    return user

  2. i’m sorry i am trying to access the custom fields from UserCreationForm and they bring attribute error that the User objects doesn’t have such fields, how do i solve the error?! how can i use them from request.user in

Leave a Reply

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