| 1 | from django.utils.decorators import method_decorator
|
|---|
| 2 |
|
|---|
| 3 | def DecoratorMixin(decorator):
|
|---|
| 4 | """
|
|---|
| 5 | Convert a classic view decorator into a Mixin for use in class-based views.
|
|---|
| 6 |
|
|---|
| 7 | Example:
|
|---|
| 8 |
|
|---|
| 9 | LoginRequired = DecoratorMixin(login_required)
|
|---|
| 10 | CanChangeThing = DecoratorMixin(permission_required('thing.change_thing'))
|
|---|
| 11 |
|
|---|
| 12 | class MyView(LoginRequired, CanChangeThing, View):
|
|---|
| 13 | ...
|
|---|
| 14 |
|
|---|
| 15 | """
|
|---|
| 16 | class Mixin(object):
|
|---|
| 17 | @method_decorator(decorator)
|
|---|
| 18 | def dispatch(self, *args, **kwargs):
|
|---|
| 19 | return super(Mixin, self).dispatch(*args, **kwargs)
|
|---|
| 20 | # copy name and module of the decorator to the mixin class
|
|---|
| 21 | Mixin.__module__, Mixin.__name__ = decorator.__module__, decorator.__name__
|
|---|
| 22 | return Mixin
|
|---|