Commit 3dbe8804 by Alex Gaynor

Fixed #9. COrrectly uniquify slugs.

parent b4c21524
from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes.generic import GenericForeignKey from django.contrib.contenttypes.generic import GenericForeignKey
from django.db import models from django.db import models, IntegrityError
from django.template.defaultfilters import slugify from django.template.defaultfilters import slugify
...@@ -12,9 +12,17 @@ class Tag(models.Model): ...@@ -12,9 +12,17 @@ class Tag(models.Model):
return self.name return self.name
def save(self, *args, **kwargs): def save(self, *args, **kwargs):
if not self.pk: if not self.pk and not self.slug:
self.slug = slugify(self.name) self.slug = slug = slugify(self.name)
super(Tag, self).save(*args, **kwargs) i = 0
while True:
try:
return super(Tag, self).save(*args, **kwargs)
except IntegrityError:
i += 1
self.slug = "%s_%d" % (slug, i)
else:
return super(Tag, self).save(*args, **kwargs)
class TaggedItem(models.Model): class TaggedItem(models.Model):
......
...@@ -62,6 +62,10 @@ class AddTagTestCase(BaseTaggingTest): ...@@ -62,6 +62,10 @@ class AddTagTestCase(BaseTaggingTest):
with self.assert_raises(ValueError): with self.assert_raises(ValueError):
f.tags.all() f.tags.all()
def test_unique_slug(self):
apple = Food.objects.create(name="apple")
apple.tags.add("Red", "red")
class LookupByTagTestCase(BaseTaggingTest): class LookupByTagTestCase(BaseTaggingTest):
def test_lookup_by_tag(self): def test_lookup_by_tag(self):
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment