Skip to content

Instantly share code, notes, and snippets.

Created March 9, 2015 12:39
Show Gist options
  • Select an option

  • Save anonymous/ae876278c1d710bfd8cb to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/ae876278c1d710bfd8cb to your computer and use it in GitHub Desktop.
middleware.py
class RedirectFallbackMiddleware(object):
def process_response(self, request, response):
if response.status_code != 404:
return response # No need to check for a redirect for non-404 responses.
path = request.path
try:
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path=path)
except Redirect.DoesNotExist:
r = None
if r is None and settings.APPEND_SLASH:
# Try removing the trailing slash.
try:
r = Redirect.objects.get(site__id__exact=settings.SITE_ID,
old_path=path[:path.rfind('/')]+path[path.rfind('/')+1:])
except Redirect.DoesNotExist:
pass
if r is not None:
if r.new_path == '':
return http.HttpResponseGone()
return http.HttpResponseRedirect(r.new_path)
# No redirect was found. Return the response.
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment