From dbd449b708f546f2572769a30e54349be5f3bca0 Mon Sep 17 00:00:00 2001 From: Konstantin Kostov Date: Thu, 14 Mar 2024 03:27:01 +0100 Subject: [PATCH] Redirect slugs to blogposts --- blog/middleware.py | 28 ++++++++++++++++++++++++++++ iamkonstantin_web/settings/base.py | 1 + 2 files changed, 29 insertions(+) create mode 100644 blog/middleware.py diff --git a/blog/middleware.py b/blog/middleware.py new file mode 100644 index 0000000..a429360 --- /dev/null +++ b/blog/middleware.py @@ -0,0 +1,28 @@ +from django.http import Http404, HttpResponseRedirect +from django.urls import resolve + + +class BlogRedirectMiddleware: + def __init__(self, get_response): + self.get_response = get_response + + def __call__(self, request): + # Code to be executed for each request before + # the view (and later middleware) are called. + + response = self.get_response(request) + + # Check if the response is 404 and not a request for /blog/ + if (response.status_code == 404 and + not (request.path.startswith('/blog/') or request.path.startswith('/media/'))): + new_path = f'/blog{request.path}' + try: + # Check if the new URL with /blog/ exists + resolve(new_path) + # Redirect to the new URL if it exists + return HttpResponseRedirect(new_path) + except Http404: + # If the new URL doesn't exist, return the original 404 response + pass + + return response diff --git a/iamkonstantin_web/settings/base.py b/iamkonstantin_web/settings/base.py index d2b2316..cb8186f 100644 --- a/iamkonstantin_web/settings/base.py +++ b/iamkonstantin_web/settings/base.py @@ -60,6 +60,7 @@ MIDDLEWARE = [ "django.middleware.clickjacking.XFrameOptionsMiddleware", "django.middleware.security.SecurityMiddleware", "wagtail.contrib.redirects.middleware.RedirectMiddleware", + "blog.middleware.BlogRedirectMiddleware" ] ROOT_URLCONF = "iamkonstantin_web.urls"