Creating a Custom User Model in Django
This post explains step-by-step how to create a custom User model in Django so that an email address can be used as the primary user identifier instead of a username for authentication.
Objectives
By the end of this article, you should be able to:
- Describe the difference between
AbstractUser
andAbstractBaseUser
- Explain why you should set up a custom User model when starting a new Django project
- Start a new Django project with a custom User model
- Use an email address as the primary user identifier instead of a username for authentication
- Practice test-first development while implementing a custom User model
AbstractUser vs AbstractBaseUser
The default User model in Django uses a username to uniquely identify a user during authentication. If you'd rather use an email address, you'll need to create a custom User model by either subclassing AbstractUser
or AbstractBaseUser
.
Options:
AbstractUser
: Use this option if you are happy with the existing fields on the User model and just want to remove the username field.AbstractBaseUser
: Use this option if you want to start from scratch by creating your own, completely new User model.
We'll look at both options,
AbstractUser
andAbstractBaseUser
, in this post.
The steps are the same for each:
- Create a custom User model and Manager
- Update settings.py
- Customize the
UserCreationForm
andUserChangeForm
forms - Update the admin