Quick example of extending UserCreationForm in Django

December 19th, 2011 § 0 comments

I just banged my head against this, and with no good answers float­ing around out there, I thought I’d share. In my case, I just wanted to extend the basic django.contrib.auth.forms.UserCreationForm in order to make it so when a user was added, an email address had to be sup­plied in addi­tion to the user­name and pass­word fields.

Here is a work­ing exam­ple (forms.py) — just so I don’t for­get it:

?View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
 
class UserCreateForm(UserCreationForm):
    email = forms.EmailField(required=True)
 
    class Meta:
        model = User
        fields = ("username", "email", "password1", "password2")
 
    def save(self, commit=True):
        user = super(UserCreateForm, self).save(commit=False)
        user.email = self.cleaned_data["email"]
        if commit:
            user.save()
        return user

You have to mod­ify the save method on the form to add the email to user object returned by the super call. You can use this to expose other fields on the User object as needed.

What's this?

You are currently reading Quick example of extending UserCreationForm in Django at jessenoller.com.

meta

  • Categories

  • Recent Posts