django中是否有一个类似于@login_required的装饰器,它也可以测试用户是否是超级用户?
谢谢
django中是否有一个类似于@login_required的装饰器,它也可以测试用户是否是超级用户?
谢谢
Answers:
使用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
除@user_passes_test
。
如果员工会员就足够了,你就没有需要检查用户是否是超级用户,则可以使用@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中的一项检查。
from django.contrib.auth import REDIRECT_FIELD_NAME
对于基于类的视图,创建一个可重用的装饰器:
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):
要在基于类的视图上要求超级用户而不编写新代码,请执行以下操作:
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):
...
...
...