Derek Stegelman

Snippet Sunday: Decorating a Class Based View

Sunday snippets are bits of code that I’ve found useful in past projects. I post them here in hopes that someone else will find them useful. Most of these are Github Gists and you can follow them there too if you want.

I am always needing to decorate class based views. This is a small example on how to decorate a class based view with the login required decorator. If you need to do this to a bunch of classes, you might be better of turning this into a mixin.

from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.views.generic import ListView

class ObjectList(ListView):
model = Object
paginate_by = 30
context_object_name = "objects"
template_name = "app/object_list.html"

def dispatch(self, *args, **kwargs):
return super(ObjectList, self).dispatch(*args, **kwargs)