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 methoddecorator from django.contrib.auth.decorators import loginrequired from django.views.generic import ListView

class ObjectList(ListView): model = Object paginateby = 30 contextobjectname = "objects" templatename = "app/object_list.html"

@methoddecorator(loginrequired) def dispatch(self, args, *kwargs): return super(ObjectList, self).dispatch(args, *kwargs) ```