Created
July 2, 2012 12:34
-
-
Save roxeteer/3033015 to your computer and use it in GitHub Desktop.
Create unique slugs in Django
This file contains 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 | |
def slugify_unique(value, model, slugfield="slug", max_length=None): | |
""" | |
Check against the database that the slug is unique and automatically increase a counter. | |
Optionally check that the slug doesn't grow too long for the slug field. | |
""" | |
slug = baseslug = slugify(value) | |
counter = 1 | |
while model.objects.filter(**{ slugfield: slug }).count() > 0: | |
counter += 1 | |
if max_length is not None: | |
baseslug = baseslug[:max_length - len(str(counter)) - 1] | |
slug = "%s-%d" % (baseslug, counter) | |
return slug |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment