- Author:
- humphreymurray
- Posted:
- January 10, 2011
- Language:
- Python
- Version:
- Not specified
- Score:
- 3 (after 3 ratings)
Simple wrappers around the new class-based generic views (introduced in Django 1.3) that also check permissions.
Example Usage (views.py):
from mymodule import RestrictedListView, RestrictedUpdateView
class MyListView(RestrictedListView):
model = MyModel
class MyUpdateView(RestrictedUpdateView):
model = MyModel
and so on for Create and Delete.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | from django.views import generic
from django.contrib.auth.decorators import permission_required
class RestrictedListView(generic.ListView):
''' Generic list view that checks permissions '''
def dispatch(self, request, *args, **kwargs):
@permission_required('%s.change_%s' % (self.model._meta.app_label, self.model._meta.module_name))
def wrapper(request, *args, **kwargs):
return super(RestrictedListView, self).dispatch(request, *args, **kwargs)
return wrapper(request, *args, **kwargs)
class RestrictedUpdateView(generic.UpdateView):
''' Generic update view that checks permissions '''
def dispatch(self, request, *args, **kwargs):
@permission_required('%s.change_%s' % (self.model._meta.app_label, self.model._meta.module_name))
def wrapper(request, *args, **kwargs):
return super(RestrictedUpdateView, self).dispatch(request, *args, **kwargs)
return wrapper(request, *args, **kwargs)
class RestrictedCreateView(generic.CreateView):
''' Generic create view that checks permissions '''
def dispatch(self, request, *args, **kwargs):
@permission_required('%s.create_%s' % (self.model._meta.app_label, self.model._meta.module_name))
def wrapper(request, *args, **kwargs):
return super(RestrictedCreateView, self).dispatch(request, *args, **kwargs)
return wrapper(request, *args, **kwargs)
class RestrictedDeleteView(generic.DeleteView):
''' Generic delete view that checks permissions '''
def dispatch(self, request, *args, **kwargs):
@permission_required('%s.delete_%s' % (self.model._meta.app_label, self.model._meta.module_name))
def wrapper(request, *args, **kwargs):
return super(RestrictedDeleteView, self).dispatch(request, *args, **kwargs)
return wrapper(request, *args, **kwargs)
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 8 months, 3 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 9 months ago
- Serializer factory with Django Rest Framework by julio 1 year, 3 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 4 months ago
- Help text hyperlinks by sa2812 1 year, 5 months ago
Comments
Please login first before commenting.