Created
March 31, 2011 15:16
-
-
Save jsocol/896543 to your computer and use it in GitHub Desktop.
PermissionDeniedMiddleware for Django 1.2.x
This file contains 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
""" | |
Improve PermissionDenied/HttpResponseForbidden handling in Django 1.2. | |
At some point, Django added better handling for PermissionDenied | |
and HttpResponseForbidden, including a handler403 on the ROOT_URLCONF, and, | |
I think, the ability to fall back to a generic 403.html. | |
But Django 1.2 didn't have that, as far as I know. So this middleware adds | |
it for Django 1.2 projects. | |
""" | |
from django import template | |
from django.conf import settings | |
from django.http import HttpResponseForbidden | |
if getattr(settings, 'ROOT_URLCONF'): | |
package, _, module = settings.ROOT_URLCONF.rpartition('.') | |
urls = __import__(module, fromlist=[package]) | |
else: | |
urls = None | |
class PermissionDeniedMiddleware(object): | |
"""Add a 403 handler.""" | |
def process_response(self, request, response): | |
if isinstance(response, HttpResponseForbidden): | |
if request.user.is_authenticated(): | |
if urls and hasattr(urls, 'handler403'): | |
module, _, fn = urls.handler403.rpartition('.') | |
try: | |
view = __import__(fn, fromlist=[module]) | |
except ImportError: | |
return response | |
return view(request) | |
try: | |
t = template.loader.get_template('403.html') | |
except template.TemplateDoesNotExist: | |
return response # No better idea. Reraise? | |
c = template.RequestContext(request) | |
return HttpResponseForbidden(t.render(c)) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment