0

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?

user3084860
  • 421
  • 5
  • 19
  • Can you post the whole `DashboardView`? The problem might not be in the code you posted. – Bibhas Debnath Jan 03 '14 at 21:29
  • Related: http://stackoverflow.com/questions/6069070/how-to-use-permission-required-decorators-on-django-class-based-views – sk1p Jan 03 '14 at 21:38

1 Answers1

3

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

Ben Regenspan
  • 10,058
  • 2
  • 33
  • 44