我正在尝试为 Django 编写一个“仅限员工”的装饰器,但我似乎无法让它工作:
def staff_only(error='Only staff may view this page.'):
def _dec(view_func):
def _view(request, *args, **kwargs):
u = request.user
if u.is_authenticated() and u.is_staff:
return view_func(request, *args, **kwargs)
messages.error(request, error)
return HttpResponseRedirect(request.META.get('HTTP_REFERER', reverse('home')))
_view.__name__ = view_func.__name__
_view.__dict__ = view_func.__dict__
_view.__doc__ = view_func.__doc__
return _view
return _dec
尝试从这里开始。我得到:
'WSGIRequest' object has no attribute '__name__'
但是如果我把这三行去掉,我只会得到一个无用的“内部服务器错误”。我在这里做错了什么?
此装饰器已经存在为
from django.contrib.admin.views.decorators import staff_member_required
@staff_member_required
后备箱: http://code.djangoproject.com/browser/django/trunk/django/contrib/admin/views/decorators.py
对于基于类的视图,您可以像这样装饰视图类的调度方法:
from django.contrib.admin.views.decorators import staff_member_required
from django.utils.decorators import method_decorator
@method_decorator(staff_member_required, name='dispatch')
class ExampleTemplateView(TemplateView):
...
这种风格的装饰器函数与参数化装饰器一起使用 - 例如,当您这样做时:
@staffonly(my_arguments)
def function(request):
blah
如果您实际上没有调用外部函数,即您像这样使用它:
@staffonly
def function(request):
您会得到奇怪的结果,因为函数对象将被传递给装饰器中错误的嵌套函数之一。
我使用你的装饰器,我只遇到一个错误:-
'bool' object is not callable
这个错误来自这里
if u.is_authenticated() and u.is_staff:
我将 u.is_authenticated()
更改为 u.is_authenticated
,它非常适合我