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

时间:2015-01-19 09:19:24

标签: python django python-2.7 decorator python-decorators

我为基于功能的视图创建了staff_member_required,但没有找到类方法。好吧,我试图为基于类的视图编写装饰器:

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

  / p在/ en-us / user / userdata / 7 / get()中的TypeError恰好为3   参数(2给出)

我该如何解决?

1 个答案:

答案 0 :(得分:0)

您需要使用dispatch装饰method_decorator方法。

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())),
    ...
)