在 Django 中为 class 方法制作装饰器

Making decorator for class method in Django

我成立 staff_member_required 是为了基于函数的视图,但没有找到 class 方法。好吧,我尝试为基于 class 的视图编写装饰器:

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命令启动服务器后,报错:

TypeError at /en-us/user/userdata/7/ get() takes exactly 3 arguments (2 given)

我该如何解决?

您需要使用 method_decorator.

修饰 dispatch 方法
class SetUserData(View):
    @method_decorator(cls_method_staff_member_decorator)
    def dispatch(self, *args, **kwargs):
        return super(SetUserData, self).dispatch(*args, **kwargs)

已解释here

或者在 urls 中装饰:

urlpatterns = patterns('',
    ...
    (r'^your_url/', cls_method_staff_member_decorator(SetUserData.as_view())),
    ...
)