This is replace for django.contrib.redirects.RedirectFallbackMiddleware which redirects exact matches as well as startswith matches for the redirect.old_path
I had a problem with my urls, because are dynamically generic, so I can't create one redirect entry on the database for each possible url. So I made django redirects to search any redirect with the exact match or any database entry being the head of my url, for example:
I have django redirects which redirects /calendars/3434/ --> / . But when I have a 404 on /calendars/3434/c/2009/10/23/ now it redirects properly. So my redirects now acts as /calendars/3434/*
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 | from django.contrib.redirects.models import Redirect
from django import http
from django.conf import settings
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.get_full_path()
try:
paths = [path]
current_path = request.path
while current_path and current_path != '/' and '/' in current_path:
paths.append(current_path)
current_path = current_path.rsplit('/',2)[0]+'/'
r = Redirect.objects.get(site__id__exact=settings.SITE_ID, old_path__in=paths)
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.HttpResponsePermanentRedirect(r.new_path)
# No redirect was found. Return the response.
return response
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
Please login first before commenting.