Skip to content

Instantly share code, notes, and snippets.

@prestontimmons
Created September 6, 2011 16:34
Show Gist options
  • Save prestontimmons/1198079 to your computer and use it in GitHub Desktop.
Save prestontimmons/1198079 to your computer and use it in GitHub Desktop.
slugify model on save
from django.template.defaultfilters import slugify as django_slugify
class MyModel(models.Model):
def save(*args, **kwargs):
# Build our slug from the name, keeping it short for
# linkability, but still guarantee uniqueness
if not self.pk and self.slug:
self.slug = self.slugify(self.slug)
i = 0
while True:
i += 1
try:
sid = transaction.savepoint()
result = super(MyModel, self).save(*args, **kwargs)
transaction.savepoint_commit(sid)
return result
except IntegrityError:
transaction.savepoint_rollback(sid)
self.slug = self.slugify(self.slug, i)
super(MyModel, self).save(*args, **kwargs)
def slugify(self, name_part, i=None):
slug = django_slugify(name_part)
if i is not None:
slug += "-%d" % i
return slug
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment