【问题标题】:Django Decorator Attribute Error for Class Based Views基于类的视图的 Django 装饰器属性错误
【发布时间】:2014-01-21 16:07:38
【问题描述】:

我正在尝试在我的 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'

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

【问题讨论】:

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


【解决方案1】:

您可以像这样使用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

【讨论】:

  • 感谢您的回答。我知道我忘记了一些简单的事情。
猜你喜欢
  • 2017-03-08
  • 2014-05-19
  • 2020-07-07
  • 2014-10-20
  • 1970-01-01
  • 2023-02-07
  • 1970-01-01
  • 2011-08-29
  • 1970-01-01
相关资源
最近更新 更多