Search code examples
pythondjangodjango-modelsviewdjango-views

how to check is staff is True before login into dashboard which i have created by myself in Django?


I have created a dashboard and in my dashboard superuser creates the username, password, and all this thing but in my dashboard, I want to check first the username is staff or not before login into the dashboard. how to do that? can anyone help me

from django.shortcuts import redirect, render
from django.contrib import auth, messages
from orderkitchen.models import kitchenData 
from django.contrib.auth.models import User

def login_dashboard(request):

    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']
        user = auth.authenticate(username = username, password = password)
        if user is not None:
            auth.login(request,user)
            messages.success(request, 'You are Logged in')
            return redirect('dashboard')
            
        else:
            messages.error(request,'Your Username or Password is incorrect')
            return redirect('login_dashboard')
        return
    else:
        return render(request,'accounts/dashboard_login.html')

def dashboard(request):
    return render(request, 'accounts/dashboard.html')

only the staff status is True then only then can logged in

enter image description here


Solution

  • You can check the status after authenticate if it returns not None as

    from django.shortcuts import redirect, render
    from django.contrib import auth, messages
    from orderkitchen.models import kitchenData 
    from django.contrib.auth.models import User
    
    def login_dashboard(request):
    
        if request.method == 'POST':
            username = request.POST['username']
            password = request.POST['password']
            user = auth.authenticate(username = username, password = password)
            if user is not None and user.is_staff == True:
                auth.login(request,user)
                messages.success(request, 'You are Logged in')
                return redirect('dashboard')
            
            else:
                messages.error(request,'Your Username or Password is incorrect')
                return redirect('login_dashboard')
            return
        else:
            return render(request,'accounts/dashboard_login.html')
    
    def dashboard(request):
        return render(request, 'accounts/dashboard.html')