Skip to content

Instantly share code, notes, and snippets.

@krzysztofjeziorny
Last active December 5, 2023 16:51
Show Gist options
  • Save krzysztofjeziorny/828372346ee278a79eedc46b7ddd7384 to your computer and use it in GitHub Desktop.
Save krzysztofjeziorny/828372346ee278a79eedc46b7ddd7384 to your computer and use it in GitHub Desktop.
Wagtail URL 'shortener' redirecting from /item/id to the page's address
<!-- add to <head> to prevent duplicate content issues in search engine optimization -->
<link rel="canonical" href="{{ page.full_url }}">
from .views import item_redirect
# ... Wagtail urlpatterns as usual ...
urlpatterns = urlpatterns + [
# Redirect all pages from the `/item/:id` address to their respective URLs
path('item/<int:id>/', item_redirect, name="item_redirect"),
# For anything not caught by a more specific rule above, hand over to
# Wagtail's page serving mechanism. This should be the last pattern in
# the list:
path("", include(wagtail_urls)),
]
from django.shortcuts import get_object_or_404, redirect
from wagtail.models import Page
def item_redirect(request, id):
"""
Redirect all pages from a `/item/id` shortcut to their URLs
"""
# Get the page with the specified id
page = get_object_or_404(Page, id=id)
# Redirect to the original URL of the page
return redirect(page.url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment