Question

I'm trying to use a decorator on the dispatch methods of several Class Based Views in my Django app. Here is one example view I tried:

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)

With the following decorator:

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

Which gets me the following error:

AttributeError at /dashboard/

'DashboardView' object has no attribute 'user'

How can I get the decorator to retrieve the current user with this view?

Was it helpful?

Solution

You can convert the old-style decorator to a method decorator by using django.utils.decorators.method_decorator like this:

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)

Related documentation is here: Introduction to Class-based Views

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top