102

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

谢谢

4

7 回答 7

173

使用user_passes_test装饰器:

from django.contrib.auth.decorators import user_passes_test

@user_passes_test(lambda u: u.is_superuser)
def my_view(request):
    ...
于 2012-08-17T10:09:56.930 回答
87

如果员工成员足够,并且您不需要检查用户是否为超级用户,则可以使用@staff_member_required装饰器:

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

@staff_member_required
def my_view(request):
    ...
于 2015-11-05T22:22:08.727 回答
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里改了一个check。

于 2017-09-20T09:27:20.920 回答
4

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

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):
        # ...
于 2019-03-02T09:49:18.583 回答
4

我推荐使用 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):
于 2020-01-06T15:57:13.497 回答
2

如果您有您的用户个人资料,您可以简单地执行此操作

@login_required
@user_passes_test(lambda u: True if u.profile.role==2 else False )
def add_listing(request):
    #...
于 2020-03-14T14:38:33.257 回答
1

要在基于类的视图上要求超级用户而不编写新代码:

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):
    ...
    ...
    ...
于 2020-06-02T18:22:22.573 回答