Created
September 6, 2011 16:34
-
-
Save prestontimmons/1198079 to your computer and use it in GitHub Desktop.
slugify model on save
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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