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