In this article, we'll explore how to create a new custom Django user model in case the default user model doesn't fit with your project.
This recommended only on new project, if you're adding a custom user model to an existing project, be aware of migration issues. Read Django docs.
Set Up Your Django Project
shellpip install django
Create a new Django project:
shelldjango-admin startproject myproject
Create Custom User Model
Option 1: Using AbstractUser
In models.py
file within Django app, define custom user model by subclassing AbstractUser
:
Choose this option if you are satisfied with the existing fields in the user model and just want to remove or add some field.
pythonfrom django.contrib.auth.models import AbstractUser class CustomUser(AbstractUser): # Add any custom fields here pass
Option 2: Using AbstractBaseUser
Alternatively, if you need more control over the user model, you can subclass AbstractBaseUser
and define all fields and methods yourself:
Choose this option if you want to build a completely new user model from scratch.
pythonfrom django.contrib.auth.models import AbstractBaseUser, BaseUserManager class CustomUserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password, ) user.is_admin = True user.is_staff = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(unique=True) # Add any additional fields here is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' def __str__(self): return self.email def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, app_label): return self.is_admin
Configure Your Custom User Model in settings.py
In your project's settings.py
, specify the custom user model you created:
pythonAUTH_USER_MODEL = 'myapp.CustomUser' # Replace 'myapp' with the name of your Django app
Make Migrations and Migrate
Generate database migrations for your custom user model:
shellpython manage.py makemigrations
Apply the migrations to your database:
shellpython manage.py migrate
Update Django Admin
If you are using Django Admin, you may need to update it to work with your custom user model. Update admin.py
:
pythonfrom django.contrib import admin from django.contrib.auth.admin import UserAdmin from .models import CustomUser class CustomUserAdmin(UserAdmin): model = CustomUser # Customize your admin view as needed admin.site.register(CustomUser, CustomUserAdmin)
Now, we can use customUserModel
with our project.