Login

Class based generic views that automatically check permissions

Author:
humphreymurray
Posted:
January 10, 2011
Language:
Python
Version:
Not specified
Tags:
generic-views permissions class-based
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

  1. Generic views with row-level permission handling by mwicat 4 years ago
  2. Custom model field for Frame or Box by binishkaspar 4 years, 3 months ago
  3. Row-Level, URL-based permissions for FlatPages by bradmontgomery 5 years, 11 months ago
  4. Model Hooks by jakecr 5 years, 4 months ago
  5. Model merging function by xaralis 4 years, 6 months ago

Comments

Please login first before commenting.