django @login_required装饰器,用于超级用户


86

django中是否有一个类似于@login_required的装饰器,它也可以测试用户是否是超级用户?

谢谢

Answers:



75

如果员工会员就足够了,你就没有需要检查用户是否是超级用户,则可以使用@staff_member_required装饰:

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

@staff_member_required
def my_view(request):
    ...

34
当我来到这里时,这就是我想要的,这就是为什么将其放在这里,我将其留在这里,因为我认为它对其他人可能有用。
2015年

3
是@ Bit68。我正在寻找它:)
Shiv Shankar

7

如果您想要具有与@staff_member_required类似的功能,则可以轻松编写自己的装饰器。以@staff_member为例,我们可以执行以下操作:

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

此示例是经过修改的staff_member_required,只是更改了lambda中的一项检查。


4
您还将需要此导入语句:) from django.contrib.auth import REDIRECT_FIELD_NAME
Bryan Tarpley

3

对于基于类的视图,创建一个可重用的装饰器:

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):
        # ...

2

如果您拥有用户个人资料,则只需执行此操作

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

1

我建议使用Mixins,例如:

from django.contrib.auth.mixins import UserPassesTestMixin


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

然后,您可以添加SuperUserCheckView课程:

class MyView(SuperUserCheck, View):

0

要在基于类的视图上要求超级用户而不编写新代码,请执行以下操作:

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):
    ...
    ...
    ...
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.