Login

Decorate class-based views with regular decorators

Author:
jeffheard
Posted:
January 1, 2015
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

Decorating a whole view involves overriding the dispatch method so you can decorate it, even if all you do is a passthrough. This creates a class decorator for decorating CBVs. For example, if you want to make a view require a login:

@decorate_dispatch(login_required)  
class MyCBV(TemplateView):
    ...
1
2
3
4
5
6
7
from django.utils.decorators import method_decorator

def decorate_dispatch(decorator):
    def decorate(cls):
        setattr(cls, 'dispatch', method_decorator(decorator)(cls.dispatch))
        return cls
    return decorate

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.