Implement a Custom User Model in Django

Introduction

Set up a Custom User Model in Django.

This article is part of the Build Django app on Docker and deploy it to AWS Fargate (https://qiita.com/keita_gawahara/items/66e58a6eed5c0c5f31d2).

Reasons to use Custom User Model

By default, Django has a user model set. However, when you actually create an app, there will always be a time when you want to change the user model to match the app you created. It is very difficult to modify the user model after coding to some extent, so it is recommended to set the Custom User Model from the beginning of the project.

About implementation of Custom User Model

To implement the Custom User Model, use the "AbstractUser" class or the "AbstractBaseUser" class. The "AbstractUser" class is a simple way to extend the default user fields and authentication. The method of using the "AbstractBaseUser" class increases the amount of coding, but it can be customized in more detail.

This time, we will implement it using "Abstract User". I also used "Abstract User" to customize the user model in the project I was involved in developing. For general user management, "Abstract User" is sufficient.

Preparation

Implement the Custom User Model in the project created with Using PostgreSQL with Docker + Django.

Add users app

First, create a users app that manages custom users with the startapp command. Then add the Custom User Model related code to setting.py.

docker-compose exec web python manage.py startapp users

Let's add the created users to setting.py. Also, at the end, state that the custom user model will be used instead of the default user model.

setting.py


INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    # Local
    'users.apps.UsersConfig', #add to
]
...
AUTH_USER_MODEL = 'users.CustomUser' #add to

Add Custom User to model

Create a CustomUser class in models.py. This time, we will not add fields from the default user model, so add pass directly under it. If you want to set your own field, please add the field here.

users/models.py


from django.contrib.auth.models import AbstractUser
from django.db import models

class CustomUser(AbstractUser):
    pass

Creating Custom User Forms

Create users / forms.py and add the following code.

users/form.py


from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UserChangeForm


class CustomUserCreationForm(UserCreationForm):

    class Meta(UserCreationForm):
        model = get_user_model()
        fields = ('email', 'username',)


class CustomUserChangeForm(UserChangeForm):

    class Meta(UserChangeForm):
        model = get_user_model()
        fields = ('email', 'username',)

Custom User Admin settings

Add the following code to admin.py.

users/admin.py


from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin

from .forms import CustomUserCreationForm, CustomUserChangeForm

CustomUser = get_user_model()


class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = ['email', 'username',]

admin.site.register(CustomUser, CustomUserAdmin)

This completes the settings. Finally, let's migrate.

docker-compose exec web python manage.py makemigrations users
docker-compose exec web python manage.py migrate

Recommended Posts

Implement a Custom User Model in Django
Implement a custom View Decorator in Pyramid
Model changes in Django
What is a dog? Django--Create a custom user model 2
Implementation of custom user model authentication in Django REST Framework with djoser
Implement follow functionality in Django
How to use fixture in Django to populate sample data associated with a user model
User is not added successfully after creating a custom User model
Implement a date setter in Tkinter
Implement a Django app on Hy
[My note] Django's custom User model
Custom state space model in Python
Create a LINE Bot in Django
Install Django in a pipenv virtual environment
Django: Migration doesn't reflect model in DB
Let's implement a custom prefix on discord.py!
Use a scikit-learn model trained in PySpark
Create a model for your Django schedule
Sum of variables in a mathematical model
Implement DeepChem's GraphGatherLayer in PyTorch's custom layer
Dynamically specify a ModelChoiceField queryset in Django
Get a reference model using Django Serializer
Implement a model with state and behavior
How to implement Rails helper-like functionality in Django
Django model: ManyToManyField
Models in Django
Start Django in a virtual environment with Pipenv
If you want to display values using choices in a template in a Django model
Enable Django https in just a few lines
Build a Django environment with Vagrant in 5 minutes
How to implement a gradient picker in Houdini
Implement Custom Authorizer for Firebase Authentication in Chalice
I tried to implement TOPIC MODEL in Python
Create a custom search command in Splunk (Streaming Command)
Send an email with a user other than EMAIL_HOST_USER written in settings in django
Create a simple momentum investment model in Python
Pass login user information to view in Django
Use a custom error page in python / tornado
Configure a module with multiple files in Django
Implement a discrete-time logistic regression model with stan
How to create a Rest Api in Django
Until you create a new app in Django
Forms in Django
I want to easily implement a timeout in python
How to get multiple model objects randomly in Django
I tried to implement a pseudo pachislot in Python
Implement the Django user extension and register the attached information
[Django] Implement image file upload function without using model
How to reference static files in a Django project
[Django] Give Form a dynamic initial value from Model
Implement hierarchical URLs with drf-nested-routers in Django REST framework
Create a Django schedule
Investigate django user management
Implement recommendations in Python
Implement XENO in python
How to create a record by pasting a relation to the inheriting source Model in the Model inherited by Django
dict in dict Makes a dict a dict
A story that makes it easier to see Model debugging in the Django + SQLAlchemy environment
[Django] Field names, user registration, and login methods that can be used in the User model
Custom sort in Python3
Implement sum in Python