Django Custom User model and Authentication

129 Views Asked by At

i want to create a user model for three types of user role Student, Teacher and Principal By inheriting AbstractUser in Django

how can i do this.? i have seen many projects but the create a single table for authentication of all students, teachers and principal

and link it to another model such as StudentProfile, TeacherProfile and PrincipalProfile using onetoone field

i want that all student information such as their username, email, password,... to be saved in a single table similarly i want all info for teacher to be save in single table (Not in student table) same for principal

Is it possible? If yes how can i perform their authentication

1

There are 1 best solutions below

0
Ahtisham On

You can create one model User with role choices and have that one to one relation with Profile model like this:

models:

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

class User(AbstractBaseUser):
    STUDENT = 1
    TEACHER = 2
    PRINCIPAL = 3
      
    ROLE_CHOICES = (
       (STUDENT, 'Student'),
       (TEACHER, 'Teacher'),
       (PRINCIPAL, 'Principal'),
    )
    role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True)

class Profile(model.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

Here is the full example source and docs for Abstract User

You don't have to use Abstract User model you can extend from User model itself.