How to implement a Custom User Model in Django

Django comes with a built-in user model, but using it as-is is not recommended—even in the official Django documentation. Instead, it is generally advised to implement and use a custom user model from the beginning.

Custom user model implementation should be done before the initial migration

Implementing a custom user model should be done right after setting up your Django environment.

This is because once you’ve run the initial migrations with the default user model, implementing a custom user model afterward becomes quite difficult and cumbersome.

While it’s not impossible to switch to a custom user model before the production release, it’s still not something that can be resolved with a single command. Therefore, it’s best to implement the custom user model before running the initial migration.

How to Implement a Custom User Model

There are mainly two approaches to implementing a custom user model in Django. In this case, I’ll introduce the simpler method that’s easier to implement.

Add an app for account management, and define the custom user model in the models.py file created within that app’s folder.

from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
    birthday = models.DateField()

Next, add the following line to your settings.py file.

The example below assumes you’ve implemented the custom user model in an app called account.

AUTH_USER_MODEL = "account.CustomUser"

After that, run the following two commands to complete the migration for the custom user model. (This assumes you’re using Docker Compose and have a container named web.)

docker-compose run web python3 manage.py makemigrations
docker-compose run web python3 manage.py migrate

That’s how you implement a custom user model in Django.

In this guide, we went over the simpler method, but there are more flexible ways to define a user model as well. I’ll cover those advanced approaches another time.

おすすめの記事