Python 在Django中为类方法制作装饰器
我发现基于函数的视图需要staff\u member\u,但没有找到类方法。我试图为基于类的视图编写decorator:Python 在Django中为类方法制作装饰器,python,django,python-2.7,decorator,python-decorators,Python,Django,Python 2.7,Decorator,Python Decorators,我发现基于函数的视图需要staff\u member\u,但没有找到类方法。我试图为基于类的视图编写decorator: from django.contrib.admin.views.decorators import staff_member_required from django.views.generic import View def cls_method_staff_member_decorator(func): def wrapper(self, request, *a
from django.contrib.admin.views.decorators import staff_member_required
from django.views.generic import View
def cls_method_staff_member_decorator(func):
def wrapper(self, request, *args, **kwargs):
return staff_member_required(view_func=func)(request, *args, **kwargs)
return wrapper
class SetUserData(View):
http_method_names = ['get', ]
@cls_method_staff_member_decorator
def get(self, request, user_id):
# ... some actions with data
但在通过runserver命令启动服务器后,出现以下错误:
/en us/user/userdata/7/get处的TypeError正好取3
论据2
如何修复它?您需要使用decorator方法装饰分派方法
解释
或者在URL中修饰:
class SetUserData(View):
@method_decorator(cls_method_staff_member_decorator)
def dispatch(self, *args, **kwargs):
return super(SetUserData, self).dispatch(*args, **kwargs)
urlpatterns = patterns('',
...
(r'^your_url/', cls_method_staff_member_decorator(SetUserData.as_view())),
...
)