41👍
✅
You use @method_decorator
on the dispatch
method of the class:
from django.views.generic import View
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import user_passes_test
class MyView(View):
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(MyView, self).dispatch(*args, **kwargs)
26👍
Building on @Chris Pratt’s answer, you’ll probably want to do this in multiple view classes so it makes sense to turn it into a mixin.
class SuperuserRequiredMixin(object):
@method_decorator(user_passes_test(lambda u: u.is_superuser))
def dispatch(self, *args, **kwargs):
return super(SuperuserRequiredMixin, self).dispatch(*args, **kwargs)
Usage
class MyView(SuperuserRequiredMixin, View):
def get(self, request):
...
To prevent unexpected MRO bugs, ensure the mixin is the first inherited class.
You can implement a LoginRequiredMixin
, or any other common tests you use in your app, in the same way.
Edit: Django 1.9 adds AccessMixin, LoginRequiredMixin, PermissionRequiredMixin, and UserPassesTestMixin
- [Django]-Writing a custom management command with args and options – explanation of fields needed
- [Django]-How to test custom django-admin commands
- [Django]-Django REST Framework image upload
1👍
I have used the @view_decorator from this snippet: http://djangosnippets.org/snippets/2505/ to wrap my normal function decorators.
- [Django]-How to execute a GROUP BY … COUNT or SUM in Django ORM?
- [Django]-How to make an Inner Join in django?
- [Django]-Django query negation
- [Django]-In the Django admin interface, is there a way to duplicate an item?
- [Django]-How to receive json data using HTTP POST request in Django 1.6?
- [Django]-Django: sqlite for dev, mysql for prod?
Source:stackexchange.com