Managing Wagtail redirects as pages
egj wagtail
(9/26/2014) UPDATE: Alejandro Varas has published an extended version of this, which is able to redirect to an external URL or a hosted Document in addition to internal pages. He also added the panel definition that my code was missing.
Wagtail has a built in “Redirects” system that lets you set up redirects for particular URLs. These are managed independently of your site’s Page tree, which has a few disadvantages:
- The editor’s user interface just provides a raw URL field for the source of the redirect, instead of letting you add redirects from within the Explorer and see them in their urlspace context.
- If you set up a redirect at /my-page/redirect-url/ then the “my-page” parent won’t have any knowledge of the redirect that’s underneath it. This means you’d need to do extra work and database queries any time you want to do something with those redirects in the page hierarchy, like displaying them in their parent page’s navigation menus.
- You lose all the other built in features of pages, like search integration, workflow, versioning, etc.
So, for typical usage (e.g. avoiding link breakage when pages move around) the built in system is appropriate, but sometimes you may need to treat redirects a bit more like fully managed content.
Luckily it’s easy to set up a custom Page type which acts as a redirect. You just need to override the “serve” method from the core Page class, for example:
from django.shortcuts import redirect class PageAlias(Page): alias_for_page = models.ForeignKey(’wagtailcore.Page’, related_name=’aliases’) def serve(self, request): return redirect(self.alias_for_page.url, permanent=False)
Now you have a new Page type which editors can add anywhere in their site tree, using the standard user experience including the page chooser interface, which will redirect to your chosen page instead of rendering a template.
(Note that `permanent=False` in the redirect -- returning a permanent redirect will mean you can't reliably change the page after it's been published, since browsers cache permanent redirects really aggressively.)