Created
April 28, 2010 10:39
-
-
Save stephenmcd/381981 to your computer and use it in GitHub Desktop.
Auto unique slugs for Django models
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
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