Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django @login_required decorator for a superuser

Is there a decorator in django similar to @login_required that also tests if the user is a superuser?

Thanks

like image 658
MadMaardigan Avatar asked Aug 17 '12 10:08

MadMaardigan


3 Answers

Use the user_passes_test decorator:

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def my_view(request):
    ...
like image 135
dgel Avatar answered Oct 24 '22 10:10

dgel


In case staff membership is sufficient and you do not need to check whether the user is a superuser, you can use the @staff_member_required decorator:

from django.contrib.admin.views.decorators import staff_member_required

@staff_member_required
def my_view(request):
    ...
like image 33
Bit68 Avatar answered Oct 24 '22 12:10

Bit68


If you want to have similar functionality to @staff_member_required you can easily write your own decorator. Taking @staff_member as an example we can do something like this:

from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.admin.views.decorators import user_passes_test

def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,
                   login_url='account_login_url'):
    """
    Decorator for views that checks that the user is logged in and is a
    superuser, redirecting to the login page if necessary.
    """
    actual_decorator = user_passes_test(
        lambda u: u.is_active and u.is_superuser,
        login_url=login_url,
        redirect_field_name=redirect_field_name
    )
    if view_func:
        return actual_decorator(view_func)
    return actual_decorator

This example is a modified staff_member_required, just changed one check in lambda.

like image 30
koradon Avatar answered Oct 24 '22 12:10

koradon