有没有在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):
...
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
(该语句可将 django
中的 REDIRECT_FIELD_NAME
导入到当前代码中使用) - Bryan Tarpley对于基于类的视图,创建可重用的装饰器:
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):
# ...
我建议使用Mixin,例如:
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):
...
...
...
'''
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')
'''
@user_passes_test
之外使用@staff_member_required
。 - phy25