Created
November 5, 2012 01:22
-
-
Save havencruise/4014709 to your computer and use it in GitHub Desktop.
Django - Custom decorator involving processing the request
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Django provides some great and easy to use decorators | |
# that accept simple functions that you could use to | |
# perform certain tests on the user. However, if your test | |
# depends on some parameter within the request object (like mine did), | |
# you could do something like: | |
from django.contrib.auth import REDIRECT_FIELD_NAME | |
from django.utils.decorators import available_attrs | |
from django.utils.http import urlquote | |
from django.http import HttpResponseRedirect | |
from functools import wraps | |
def my_test_func(request): | |
# Do some foobar | |
return True # or False | |
def is_super_user(): | |
def user_is_admin(redirect_field_name = REDIRECT_FIELD_NAME): | |
from django.conf import settings | |
login_url = settings.LOGIN_URL | |
def decorator(view_func): | |
# You can do any pre processing here before control | |
# is handed over to the view | |
def _wrapped_view(request, *args, **kwargs): | |
test = my_test_func(request) # Returns true or false | |
if test: # if user passes test | |
return view_func(request, *args, **kwargs) | |
path = urlquote(request.get_full_path()) | |
tup = login_url, redirect_field_name, path | |
return HttpResponseRedirect('%s?%s=%s' % tup) | |
return wraps( | |
view_func, | |
assigned = available_attrs(view_func))(_wrapped_view) | |
return decorator | |
return user_is_admin() | |
# Usage in views.py - User cannot see the dashboard unless he passes the test. | |
@is_super_user() | |
def dashboard(request): | |
return render_to_response('dashboard.html', {'msg': 'Hello world'}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment