如何使用基于django类的视图和装饰器将数据附加到视图方法?

时间:2012-10-15 07:21:57

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

我有以下装饰者:

def my_decorator(setting_value):

    def actual_decorator(func):
        func.my_setting = setting_value
        return func

    return actual_decorator

我正试图在上下文处理器中阅读my_setting,如下所示:

# Resolve the url
try:
    page_resolve = resolve(request.path_info)
except Resolver404:
    return {}

# Get the page view function
page_view = page_resolve.func

if (page_view.my_setting):
    return extra_context_data
else
    return {}

当使用CBV时,整个方案都会崩溃。如何使装饰器与FBV和CBV兼容?

1 个答案:

答案 0 :(得分:0)

将装饰器应用于dispatch功能:

class MyView(View):
    @my_decorator
    def dispatch(self, *args, **kwargs):
        return super(MyView, self).dispatch(*args, **kwargs)