Quickly adding redirects to wagtail

Recently I needed to add a large number of redirects to wagtail according to a specific pattern, because of bad links that were created owing to some bad parsing of /feed/ URLs. Redirects in wagtail use the wagtail.contrib.redirects.models.Redirect model, and this is a quick and dirty script to automatically add them.

Full documentation for redirects can be found here.

from wagtail.contrib.redirects.models import Redirect 
urls_txt = """https://www.mycanadapayday.com/blog/4-habits-of-millionaires-canadians-should-knowfeed/
https://www.mycanadapayday.com/blog/5-creative-ways-to-save-during-holiday-travelfeed/
https://www.mycanadapayday.com/blog/5-everyday-ways-to-save-when-you-buy-online-and-in-real-timefeed/
https://www.mycanadapayday.com/blog/7-new-ways-to-pay-off-your-debt-fasterfeed/
https://www.mycanadapayday.com/blog/7-ways-you-can-rent-even-with-bad-creditfeed/
https://www.mycanadapayday.com/blog/you-can-celebrate-canada-day-on-a-family-friendly-budgetfeed/""" 
def main():
    urls = urls_txt.split('\n')
    for url in urls:
        if 'feed' not in url:
            continue
        newurl = re.sub('feed/$', '', url)
        print('redir', url, 'to', newurl)
        old_path = re.sub(r'https://www.mycanadapayday.com', '', url)
        old_path = re.sub(r'/$', '', old_path)
        existing = Redirect.objects.filter(old_path=old_path).first()
        if existing:
            print('already done', url)
        else:
            print('making new redirect for', old_path, 'to', newurl)
            redirect = Redirect(
                old_path=old_path,
                is_permanent=True,
                redirect_link=newurl,
            )
            redirect.save()

And as you can see, the old link is now redirected to this correct page on saving money.

Leave a Reply

Your email address will not be published. Required fields are marked *