[Django]-Is there a way to hide part of a URL created from the Wagtail admin page tree?

4👍

I’m not entirely certain if a RoutablePageMixin is the right way to go about this, but that’s how I’ve solved this before.

Here’s an example of how you could do it with a RoutablePageMixin and a route (Note: I chopped this together pretty quickly and didn’t test it, you might need to do some adjusting)

from django.http import HttpResponseRedirect

from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from wagtail.core.models import Page

from blog.models import BlogPage


class HomePage(RoutablePageMixin, Page):
    """A home page class."""

    # HomePage Fields here...

    # This route will collect the blog slug
    # We'll look for the live BlogPost page.
    @route(r"^(?P<blog_slug>[-\w]*)/$", name="blog_post")
    def blog_post(self, request, blog_slug, *args, **kwargs):
        try:
            # Get the blog page
            blog_page = BlogPage.objects.live().get(slug=blog_slug)
        except BlogPage.DoesNotExist:
            # 404 or post is not live yet
            return HttpResponseRedirect("/")
        except Exception:
            # Handle your other exceptions here; here's a simple redirect back to home
            return HttpResponseRedirect("/")

        # Additional logic if you need to perform something before serving the blog post

        # Let the blog post page handle the serve
        return blog_page.specific.serve(request, *args, **kwargs)

One other thing to note: you’ll want to change the sitemap url on your original blog post pages so they don’t show up as /blog/blog-slug/ inside of sitemap.xml.

Leave a comment