基于类视图的Django Decorator属性错误

时间:2014-01-03 21:25:30

标签: python django decorator django-class-based-views attributeerror

我正在尝试在我的Django应用程序中使用几个基于类的视图的调度方法的装饰器。以下是我尝试的一个示例视图:

class DashboardView(TemplateView):
    template_name="omninectar/dashboard.html"

    def get_context_data(self, **kwargs):
        ....

    @active_and_login_required
    def dispatch(self, *args, **kwargs):
        return super(DashboardView, self).dispatch(*args, **kwargs)

使用以下装饰器:

active_required = user_passes_test(lambda u: u.is_active)

def active_and_login_required(view_func):
    decorated_view_func = login_required(active_required(view_func))
    return decorated_view_func

这给我带来了以下错误:

AttributeError at /dashboard/

'DashboardView' object has no attribute 'user'

如何让装饰者使用此视图检索当前用户?

1 个答案:

答案 0 :(得分:3)

您可以使用django.utils.decorators.method_decorator将旧式装饰器转换为方法装饰器:

from django.utils.decorators import method_decorator
...

class DashboardView(TemplateView):
    template_name="omninectar/dashboard.html"

    def get_context_data(self, **kwargs):
        ....

    @method_decorator(active_and_login_required)
    def dispatch(self, *args, **kwargs):
        return super(DashboardView, self).dispatch(*args, **kwargs)

相关文档在此处:Introduction to Class-based Views