View Permission Decorator Helper

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from django.http import HttpResponseRedirect
from functools import wraps

def permission(permission_tester):
    @wraps(permission_tester)
    def view_decorator(view_function):
        @wraps(view_decorator)
        def decorated_view(request, *args, **kwargs):
            if permission_tester(request, *args, **kwargs):
                view_result = view_function(request, *args, **kwargs)
            else:
                try:
                    request.user.message_set.create(message="Sorry, you don't have the necessary permissions to view that page.")
                except: pass
                view_result = HttpResponseRedirect("/")
            return view_result
        return decorated_view
    return view_decorator

More like this

  1. FieldLevelPermissionsAdmin by buriy 6 years, 7 months ago
  2. JSON decorator for views handling ajax requests by anilshanbhag 1 year, 4 months ago
  3. Allow separation of GET and POST implementations by agore 1 year, 10 months ago
  4. dropbox integration by ivarne 2 years, 1 month ago
  5. Cache view by user (and anonymous) by rafaelsdm 2 years, 8 months ago

Comments

gamaroff (on June 14, 2012):

Cool snippet. Thanks!

#

(Forgotten your password?)