Redirect slugs to blogposts
This commit is contained in:
parent
e39d5cd73c
commit
dbd449b708
2 changed files with 29 additions and 0 deletions
28
blog/middleware.py
Normal file
28
blog/middleware.py
Normal 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
|
|
@ -60,6 +60,7 @@ MIDDLEWARE = [
|
||||||
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
"django.middleware.clickjacking.XFrameOptionsMiddleware",
|
||||||
"django.middleware.security.SecurityMiddleware",
|
"django.middleware.security.SecurityMiddleware",
|
||||||
"wagtail.contrib.redirects.middleware.RedirectMiddleware",
|
"wagtail.contrib.redirects.middleware.RedirectMiddleware",
|
||||||
|
"blog.middleware.BlogRedirectMiddleware"
|
||||||
]
|
]
|
||||||
|
|
||||||
ROOT_URLCONF = "iamkonstantin_web.urls"
|
ROOT_URLCONF = "iamkonstantin_web.urls"
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue