Redirect slugs to blogposts

This commit is contained in:
Konstantin 2024-03-14 03:27:01 +01:00
parent e39d5cd73c
commit dbd449b708
2 changed files with 29 additions and 0 deletions

28
blog/middleware.py Normal file
View file

@ -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

View file

@ -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"