django 中是否有类似于@login_required 的装饰器,它也可以测试用户是否是超级用户?
谢谢
使用user_passes_test
装饰器:
from django.contrib.auth.decorators import user_passes_test
@user_passes_test(lambda u: u.is_superuser)
def my_view(request):
...
如果员工成员足够,并且您不需要检查用户是否为超级用户,则可以使用@staff_member_required
装饰器:
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
def my_view(request):
...
如果您想拥有与@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。
对于基于类的视图,创建一个可重用的装饰器:
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):
# ...
我推荐使用 Mixins,例如:
from django.contrib.auth.mixins import UserPassesTestMixin
class SuperUserCheck(UserPassesTestMixin, View):
def test_func(self):
return self.request.user.is_superuser
然后你可以添加SuperUserCheck
到View
类:
class MyView(SuperUserCheck, View):
如果您有您的用户个人资料,您可以简单地执行此操作
@login_required
@user_passes_test(lambda u: True if u.profile.role==2 else False )
def add_listing(request):
#...
要在基于类的视图上要求超级用户而不编写新代码:
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):
...
...
...