1 from django.template.defaultfilters import slugify
2 def SlugifyUniquely(value, model, slugfield="slug"):
3 """Returns a slug on a name which is unique within a model's table
5 This code suffers a race condition between when a unique
6 slug is determined and when the object with that slug is saved.
7 It's also not exactly database friendly if there is a high
8 likelyhood of common slugs being attempted.
10 A good usage pattern for this code would be to add a custom save()
11 method to a model with a slug field along the lines of:
13 from django.template.defaultfilters import slugify
17 # replace self.name with your prepopulate_from field
18 self.slug = SlugifyUniquely(self.name, self.__class__)
19 super(self.__class__, self).save()
21 Original pattern discussed at
22 http://www.b-list.org/weblog/2006/11/02/django-tips-auto-populated-fields
25 potential = base = slugify(value)
28 potential = "-".join([base, str(suffix)])
29 if not model.objects.filter(**{slugfield: potential}).count():
31 # we hit a conflicting slug, so bump the suffix & try again