#django #python #wagtail

In all Wagtail sites I setup, I enable the redirects app so that you can define redirects from the Admin pages. To set it up, you simply need to add it to the list of installed apps and to the middleware:


 2    ...
 3    'wagtail.contrib.redirects',
 4        ...
 8    # ...
 9    # all other django middlware first
10    'wagtail.contrib.redirects.middleware.RedirectMiddleware',

To finish the installation, you also need to run the migrate command to setup the database tables:

1$ ./manage.py migrate

If you then go to the settings in the menu, you'll see that a new menu item appeared called "Redirects". In there, you can specify any redirect you want.

Now, if you are migrating from another site or web application, you'll probably have a whole bunch of redirects to create at once.At that point, it becomes useful to be able to add them in an automated way. You can do this by interacting with the Redirect class directly:

 1from wagtail.core.models import Site
 3from wagtail.core import hooks
 4from wagtail.contrib.redirects.models import Redirect
 6# Get a reference to the default site
 7site = Site.objects.get(is_default_site=True)
 9# Catch duplicate errors
11    Redirect.objects.create(
12        old_path="/old-path",
13        redirect_link="/new-path",
14        site=site,
15    )
16except IntegrityError as e:
17    print('Redirect exists already')

Another use-case is to automatically create a redirect of the old slug to the new slug of a page when updating it. This can be done by using a Wagtail hook called before_edit_page:

2def create_redirect_on_slug_change(request, page):
3    if request.method == 'POST':
4        if page.slug != request.POST['slug']:
5            Redirect.objects.create(
6                old_path=page.url[:-1],
7                site=page.get_site(),
8                redirect_page=page
9            )

There's one caveat with using the Wagtail redirects app and that is that it doesn't work for all URLs. It only works for requests that pass through Wagtail. If you want to use it to setup redirects for your media files, you'll need to look for another solution.

Media assets are most often served directly by the webserver and never reach the Wagtail code. The best solution to tackle this is to handle these on the webserver level.

There are many more use-cases, so feel free to experiment!