Django Custom Auth User Model & Email Login With Roles/Groups and Permission

Poovarasu
1 min readFeb 26, 2023

Creating Custom User Model in Django:

python manage.py startapp authentication

Register the app to the settings.py file:

INSTALLED_APP = [  
........
'authentication',
]

Creating New Custom User Model Manager & User Model in authentication/models.py

from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin, BaseUserManager, Group
from django.db import models


class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('The Email is required')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save()
return user

def create_staff(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
return self.create_user(email, password, **extra_fields)

def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_superuser', True)
return self.create_staff(email, password, **extra_fields)


class User(AbstractBaseUser, PermissionsMixin):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
email = models.EmailField(unique=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']

objects = UserManager()

def get_full_name(self):
return f"{self.first_name} {self.last_name}"

def get_short_name(self):
return self.first_name

def __str__(self):
return self.email

Update ModelAdmin Details in authentication/admin.py

from django.contrib import admin
from .models import User


# Register your models here.
class UserAdmin(admin.ModelAdmin):
list_display = ('first_name', 'email', 'is_superuser', 'is_staff', 'is_active')
list_filter = ('email', 'is_staff', 'is_superuser', 'is_active')
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = (
'groups',
'user_permissions',
)
fieldsets = (
('Personal info', {'fields': ('first_name', 'last_name', 'email', 'password')}),
('Permissions', {'fields': ('is_active', 'is_staff', 'is_superuser', 'groups', 'user_permissions')}),
('Important dates', {"fields": ("last_login",)}),
)


admin.site.register(User, UserAdmin)

Register Custom User Mode to setting.py for Authentication Purposes

AUTH_USER_MODEL = 'authentication.User'

Commands to Create Migration Files & Create Tables

python manage.py makemigrations  
python manage.py migrate

--

--