109

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

Thanks

8 Answers 8

180

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):
    ...
3
96

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):
    ...
2
  • 36
    When I came here this is what I was looking for, that's why I put it here, and I will leave it here because I think it can be useful to someone else.
    – Bit68
    Nov 11, 2015 at 20:53
  • 3
    It is @Bit68. I am looking for it :) Jun 12, 2017 at 5:47
7

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.

1
  • 4
    You'll also want this import statement :) from django.contrib.auth import REDIRECT_FIELD_NAME Aug 15, 2019 at 18:45
4

For class based views, creating a reusable decorator:

from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import View


def superuser_required():
    def wrapper(wrapped):
        class WrappedClass(UserPassesTestMixin, wrapped):
            def test_func(self):
                return self.request.user.is_superuser

        return WrappedClass
    return wrapper

@superuser_required()
class MyClassBasedView(View):
    def get(self, request):
        # ...
4

I recommend using Mixins, example:

from django.contrib.auth.mixins import UserPassesTestMixin


class SuperUserCheck(UserPassesTestMixin, View):
    def test_func(self):
        return self.request.user.is_superuser

Then you can add SuperUserCheck to View class:

class MyView(SuperUserCheck, View):
2

if you have your profile of user you can simply do this

@login_required
@user_passes_test(lambda u: True if u.profile.role==2 else False )
def add_listing(request):
    #...
2

To require a superuser on a class based view without writing new code:

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test

@method_decorator(user_passes_test(lambda u: u.is_superuser), name='dispatch')
class AdminCreateUserView(LoginRequiredMixin, FormView):
    ...
    ...
    ...
0

To check if user is logged in use @login_required decorator and check if logged in user is superuser or not inside the function through if/else condition and return your response accordingly.

'''

    from django.shortcuts import HttpResponse, redirect
    from django.contrib.auth.decorators import login_required


    @login_required
    def function_name(request):
        if not request.user.is_superuser:
            return redirect('profile')
        else:
            return HttpResponse('Superuser')

'''

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.