[Answered ]-Apply Decorator in Class Based View Django according to object value

2👍

The key issue here is that you want to choose the decorator at runtime, but the usual decorator syntax is triggered at class declaration time. Fortunately, decorators are just regular Python callables, so you can apply them at runtime if you want.

There are a number of different ways you could structure this. Below I’ve created a custom decorator, since that will allow you to re-use the same code in multiple CBVs. (Of course, this could be generalized even further.)

Note that, as discussed in the documentation, the right place to apply Django decorators in a CBV is the dispatch() method; and that you need to use method_decorator to make Django’s built-in decorators suitable for use with classes.

def test_decorator(dispatch_wrapped):
    def dispatch_wrapper(self, request, *args, **kwargs):
        # presumably you're filtering on something in request or the url
        is_private = Test.objects.get(...).is_private

        decorator = vary_on_cookie if is_private else cache_page(60 * 15)
        dispatch_decorated = method_decorator(decorator)(dispatch_wrapped)

        return dispatch_decorated(self, request, *args, **kwargs)

    return dispatch_wrapper

class TestDetaiView(View):
    @test_decorator
    def dispatch(self, *args, **kwargs):
        # any custom dispatch code, or just...
        super().dispatch(*args, **kwargs)

If this is confusing, it will probably help to read more about decorators and how they’re defined and used.

0👍

Leave a comment