Skip to content

Instantly share code, notes, and snippets.

@roxeteer
Created July 2, 2012 12:34
Show Gist options
  • Save roxeteer/3033015 to your computer and use it in GitHub Desktop.
Save roxeteer/3033015 to your computer and use it in GitHub Desktop.
Create unique slugs in Django
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