Allow or limit a view to superuser only Django

If you want to allow or limit a view to superuser only in Django, you can use the @ user_passes_test decorator. This decorator will check if the user is logged in and is a superuser. If not, it will redirect the user to the login page.

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def dashboard(request):
    return "View"

The code above is a decorator that checks if the user is a superuser. If the user is a superuser, they are allowed to access the view. If the user is not a superuser, they will not be able to access the view.

We have imported user_passes_test from django.contrib.auth.decorators and then we have used it on the view that we want to secure from every user access in the application.

Was this helpful?