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:
1from mysite import settings 2 3from django.contrib.redirects.models import Redirect 4from django.contrib.sites.models import Site 5 6site = Site.objects.get(id=settings.SITE_ID) 7 8r = Redirect() 9r.site = site 10r.old_path = "/posts" 11r.new_path = "/" 12r.save()
The only tricky part is that redirects are linked to a specific site as the redirects apps requires the use of the
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
1new_name = slugify(old_name)
If this post was enjoyable or useful for you, please share it! If you have comments, questions, or feedback, you can email my personal email. To get new posts, subscribe use the RSS feed.