Home > OS >  ensure one type of user cannot log in as another type of user django
ensure one type of user cannot log in as another type of user django

Time:11-02

In Django, how can I make sure that one type of user cannot log in as another type of user? For example, if there are two types of users on my website, teachers and students, teachers should not be able to use their credentials to log in as a student and vice versa.

class Teacher(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, default="")
    email = models.CharField(max_length=200, unique=True)

class Student(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, default="")
    email = models.CharField(max_length=200, unique=True)

CodePudding user response:

you can achieve it by using user_passes_test

let us say only students should access the registration page, so you can create user_passes_function which returns True if user is student otherwise False and decorate the studen_registation view as shown in the snippet code below

from django.contrib.auth.decorators import user_passes_test
from django.shortcuts import get_object_or_404

def student_check(user):
    try:
        get_object_or_404(Student, user=user)
    except:
        return False
     else:
      return True

@user_passes_test(student_check)
def student_registration(request):
  • Related