Skip to content

Instantly share code, notes, and snippets.

@peterbe
Created June 11, 2012 23:13
Show Gist options
  • Save peterbe/2913338 to your computer and use it in GitHub Desktop.
Save peterbe/2913338 to your computer and use it in GitHub Desktop.
A very practical decorator for Django Class Based Views
from django.utils.decorators import method_decorator
def class_decorator(decorator):
def inner(cls):
orig_dispatch = cls.dispatch
@method_decorator(decorator)
def new_dispatch(self, request, *args, **kwargs):
return orig_dispatch(self, request, *args, **kwargs)
cls.dispatch = new_dispatch
return cls
return inner
# usage:
# in views.py
#
# from django.views.decorators.cache import cache_control
# from django.views.generic import View
# @class_decorator(cache_control(max_age=60))
# class MyView(View):
# filename = 'templatefile'
# def content(self, request):
# ...
@fengsi
Copy link

fengsi commented Nov 9, 2012

Looks cleaner than mixin. Thanks!

@foxx
Copy link

foxx commented Mar 27, 2014

Beautiful, thank you.

@inakidelamadrid
Copy link

Wonderful snippet, thank you!

@DevenAhluwalia
Copy link

This still is a wonderful snippet.

(Looking at the timestamp breadcrumbs, [2012,14,16,17] *Woot!)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment