After converting my blog to a Django app, I wanted to create a whole number of redirects in an automated way (because the new site has a slightly different URL structure).

I settled on using django.contrib.redirects app for the redirects.

To add them in an automated way, you can do the following:

from mysite import settings

from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site

site = Site.objects.get(id=settings.SITE_ID)

r = Redirect()
r.site = site
r.old_path = "/posts"
r.new_path = "/"
r.save()

The only tricky part is that redirects are linked to a specific site as the redirects apps requires the use of the django.contrib.sites framework.

In my case, there is only a single site which has it's ID set in the settings of my app. I'm using that ID to get the Site instance which is needed to create the redirect.

For the redirects of the posts, I wanted to have the same 'slug' functionality as what I'm using in the templates so that both match. For that, you can use the slugify method which can be found in django.template.defaultfilters:

new_name = slugify(old_name)