Added a better slugify function, monthly archives work, notes are optional now.
[~kgodey/maayanwich.git] / slugify.py
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
4
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.
9
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:
12
13                 from django.template.defaultfilters import slugify
14
15                 def save(self):
16                     if not self.id:
17                         # replace self.name with your prepopulate_from field
18                         self.slug = SlugifyUniquely(self.name, self.__class__)
19                 super(self.__class__, self).save()
20
21         Original pattern discussed at
22         http://www.b-list.org/weblog/2006/11/02/django-tips-auto-populated-fields
23         """
24         suffix = 0
25         potential = base = slugify(value)
26         while True:
27                 if suffix:
28                         potential = "-".join([base, str(suffix)])
29                 if not model.objects.filter(**{slugfield: potential}).count():
30                         return potential
31                 # we hit a conflicting slug, so bump the suffix & try again
32                 suffix += 1