简体   繁体   中英

How to attach data to view methods with django class based views and decorators?

I have the following decorator:

def my_decorator(setting_value):

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

    return actual_decorator

I'm trying to read my_setting in a context processor like so:

# 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 {}

This whole scheme falls apart when using CBVs. How do I make the decorator compatible with both FBV and CBV?

Apply the decorator to dispatch function:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM