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. Form field with fixed value by roam 1 week, 2 days ago
  2. New Snippet! by Antoliny0919 2 weeks, 2 days ago
  3. Add Toggle Switch Widget to Django Forms by OgliariNatan 3 months ago
  4. get_object_or_none by azwdevops 6 months, 3 weeks ago
  5. Mask sensitive data from logger by agusmakmun 8 months, 3 weeks ago

Comments

Please login first before commenting.