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:

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.

Filed May 10th, 2014 under wagtail

No Comments

RSS

No comments yet.

Leave a comment

To comment on this blog you will need to log in or create an account first.