kastielspb

Redirects with 404

May 19th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.83 KB | None | 0 0
  1. # settings.py
  2. INSTALLED_APPS = [
  3.     ...
  4.     'django.contrib.redirects',
  5. ]
  6. MIDDLEWARE = [
  7.     ...
  8.     'shared.middleware.redirect.RedirectFallbackMiddleware',
  9.     ...
  10. ]
  11.  
  12.  
  13. # shared.middleware.redirect.py
  14. from django.conf import settings
  15. from django.contrib.redirects.models import Redirect
  16. from django.contrib.sites.shortcuts import get_current_site
  17. from django.http import HttpResponseGone, HttpResponsePermanentRedirect
  18. from django.utils.deprecation import MiddlewareMixin
  19.  
  20. __all__ = ('RedirectFallbackMiddleware', )
  21.  
  22.  
  23. class RedirectFallbackMiddleware(MiddlewareMixin):
  24.     response_gone_class = HttpResponseGone
  25.     response_redirect_class = HttpResponsePermanentRedirect
  26.  
  27.     def process_response(self, request, response):
  28.         full_path = request.get_full_path()
  29.         current_site = get_current_site(request)
  30.  
  31.         redirect = None
  32.         try:
  33.             redirect = (
  34.                 Redirect
  35.                 .objects
  36.                 .get(site=current_site, old_path=full_path)
  37.             )
  38.         except Redirect.DoesNotExist:
  39.             pass
  40.  
  41.         if (
  42.             redirect is None
  43.             and settings.APPEND_SLASH
  44.             and not request.path.endswith('/')
  45.         ):
  46.             try:
  47.                 redirect = (
  48.                     Redirect
  49.                     .objects
  50.                     .get(
  51.                         site=current_site,
  52.                         old_path=request.get_full_path(force_append_slash=True),
  53.                     )
  54.                 )
  55.             except Redirect.DoesNotExist:
  56.                 pass
  57.  
  58.         if redirect is not None:
  59.             if redirect.new_path == '':
  60.                 return self.response_gone_class()
  61.             return self.response_redirect_class(redirect.new_path)
  62.  
  63.         # No redirect was found. Return the response.
  64.         return response
Add Comment
Please, Sign In to add comment