Custom Authentication enables us to use the authentication system as per our project needs.Every Django developer should know this.In this video, I have used Django version 4.1 and python version 3.8 to create a custom User Model.
It should be noted that run your initial database migration only after you have created your custom authentication classes otherwise you may encounter peculiar errors.
If migration already done, drop your database and recreate it. You may backup your database if required.Delete migration files if present in the migrations folder and don't delete __init__.py file. Re-install django.
At first in your app, put code for the user manager which will help us in creating users for our custom user model. Create file your-app/usersmanagers.py and copy this code:
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _
class CustomUserManager(BaseUserManager):
"it is our custom user manager"
def create_user(self, email, password, **extra_fields):
"to create an user"
if not email:
return ValueError(_("The email must be set"))
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user
def create_superuser(self, email, password, **extra_fields):
"to create a super user"
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError(_('Super user must have is_staff as True'))
if extra_fields.get('is_superuser') is not True:
raise ValueError(_('Superuser must have is_superuser as True'))
return self.create_user(email, password, **extra_fields)
Next go to your-app/models.py file and copy the code for the custom user model: (here email field will act as username)
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin
from django.utils import timezone
from .usersmanager import CustomUserManager
Create your models here.
class Users(AbstractBaseUser, PermissionsMixin):
"it is our custom user model"
email = models.EmailField(unique=True)
first_name = models.CharField(max_length=150, null=True, blank=True)
last_name = models.CharField(max_length=150, null=True, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_superuser = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = CustomUserManager()
def __str__(self):
return self.email
@property
def get_name(self):
return self.first_name + ' ' + self.last_name
class Meta:
db_table = 'users'
verbose_name_plural = 'users'
Next in the settings.py file, copy this line:
AUTH_USER_MODEL = 'test1_app.Users'
To register the users model in the django admin app, in the your-app/admin.py file, copy this code:
from django.contrib import admin
from .models import Users
Register your models here.
class UsersAdmin(admin.ModelAdmin):
list_display = ('email','first_name','last_name','date_joined','is_active','is_staff','is_superuser')
admin.site.register(Users, UsersAdmin)
Next run the following commands:
python manage.py makemigrations
python manage.py migrate
You may create super user like this:
python manage.py createsuperuser