Skip to content

Instantly share code, notes, and snippets.

@timmyomahony
Created July 12, 2012 00:14
Show Gist options
  • Save timmyomahony/3094633 to your computer and use it in GitHub Desktop.
Save timmyomahony/3094633 to your computer and use it in GitHub Desktop.
Automatic redirects when changing slugs
from django.contrib.redirects.models import Redirect
from django.contrib.sites.models import Site
class BlogPost(models.Model):
...
slug = models.CharField(unique=true, max_length=128)
@models.permalink
def get_absolute_url(def):
return ('blogpost_detail', (), { 'slug' : self.slug })
from django.db.models.signals import pre_save
from signals import create_redirect
pre_save.connect(create_redirect, sender=BlogPost, dispatch_uid="001")
def create_redirect(sender, instance, **kwargs):
if sender == BlogPost:
try:
o = sender.objects.get(id=instance.id)
if o.slug != instance.slug:
old_path = o.get_absolute_url()
new_path = instance.get_absolute_url()
# Update any existing redirects that are pointing to the old url
for redirect in Redirect.objects.filter(new_path=old_path):
redirect.new_path = new_path
# If the updated redirect now points to itself, delete it
# (i.e. slug = A -> slug = B -> slug = A again)
if redirect.new_path == redirect.old_path:
redirect.delete()
else:
redirect.save()
# Now add the new redirect
Redirect.objects.create(
site=Site.objects.get_current(),
old_path=old_path,
new_path=new_path)
except sender.DoesNotExist:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment