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):
......
...@@ -61,6 +61,10 @@ class AddTagTestCase(BaseTaggingTest): ...@@ -61,6 +61,10 @@ class AddTagTestCase(BaseTaggingTest):
f = Food() f = Food()
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):
......
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