Decorating class-based views

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
from functools import wraps
from django.utils.decorators import classonlymethod


def view_decorator(fdec, subclass=False):
    """
    Change a function decorator into a view decorator.

    https://github.com/lqc/django/tree/cbvdecoration_ticket14512
    """
    def decorator(cls):
        if not hasattr(cls, "as_view"):
            raise TypeError("You should only decorate subclasses of View, not mixins.")
        if subclass:
            cls = type("%sWithDecorator(%s)" % (cls.__name__, fdec.__name__), (cls,), {})
        original = cls.as_view.im_func
        @wraps(original)
        def as_view(current, **initkwargs):
            return fdec(original(current, **initkwargs))
        cls.as_view = classonlymethod(as_view)
        return cls
    return decorator

More like this

  1. ExtendibleModelAdminMixin by dokterbob 4 years, 5 months ago
  2. LoginRequired class-based view decorator by mjumbe 2 years, 9 months ago
  3. GeoDjango maps in admin TabularInlines by alanB 3 years, 6 months ago
  4. Resource by zvoase 5 years, 7 months ago
  5. Django JSONP Decorator by cominatchu 3 years, 6 months ago

Comments

(Forgotten your password?)