[Fixed]-Django : Authenticated different user models

1👍

If relation to User table is OneToOne, you can access it from user.student or user.teacher, so you would do it…

def login_view(request):
   if form.is_valid():
      # get user from form
      _user = form.get_user()
      user = authenticate(form.cleaned_data['username'], form.cleaned_data['password'])
      login(request, user)
      if hasattr(user, 'student'):
          # You'll return to student app
          return redirect('studen:home')
      # else
      return redirect('teacher:home')

EDIT

decorators.py

...
from django.contrib.auth.decorators import user_passes_test
def group_required(*args):
    if args:
        def decorator(user):
            if user.is_staff or user.is_superuser:
                return True
            return user.is_authenticated() and user.groups.filter(name__in=args).exists()
    else:
        decorator = lambda x: x.is_authenticated()

    return user_passes_test(decorator)
...

And use it…

...
@group_required('student')
def home_student(request):
   # some code

@group_required('teacher', 'student'):
def common_view_for_all(request):
   # some code
...

Leave a comment