Primary image for Quick Django Class Based View Decorator

Quick Django Class Based View Decorator

The recommended way to add decorators such as login_required to class based views in Django is a bit verbose. Here’s a little metaclass-producing function you may find handy:

def DecoratedDispatchMethod(actual_decorator):
    """
    If you want to decorate the Class-based View with, say, login_required,
    the recommended way is this:

        @method_decorator(login_required)
        def dispatch(self, *args, **kwargs):
            return super(MyProtectedView, self).dispatch(*args, **kwargs)

    To avoid the need of writing this ugly code again and again, one can use
    this as a metaclass of the class that needs to be protected with a decorator.

        class MyProtectedView(…):
            metaclass = DecoratedDispatchMethod(login_required)

    """
    class CBVMetaclass(type):
        def init(cls, name, bases, attrs):
            type.init(cls, name, bases, attrs)
            cls.dispatch = method_decorator(actual_decorator)(cls.dispatch)
    return CBVMetaclass
Vláďa Macek

About the author

Vláďa Macek

During his software engineering studies at Czech Technical University in Prague, Vlada’s love of things simple, straightforward and elegant attracted him to UNIX and led him towards a career as a full-time system administrator. Upon discovering …

Vláďa is no longer active with Lincoln Loop.