Skip to content

Instantly share code, notes, and snippets.

@stephenmcd
Created April 28, 2010 10:39
Show Gist options
  • Save stephenmcd/381981 to your computer and use it in GitHub Desktop.
Save stephenmcd/381981 to your computer and use it in GitHub Desktop.
Auto unique slugs for Django models
def save(self, *args, **kwargs):
"""
Create a unique slug from the title by appending an index.
"""
if self.id is None:
self.slug = slugify(self.title)
i = 0
while True:
if i > 0:
self.slug = "%s-%s" % (self.slug, i)
if not self.__class__.objects.filter(slug=self.slug):
break
i += 1
super(MyModel, self).save(*args, **kwargs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment