Limit uuslug max_length to the field max_length

This commit is contained in:
Fabio Souto 2015-05-25 19:05:54 +02:00
parent f2e487936e
commit 902ede9bdf
3 changed files with 47 additions and 1 deletions

View file

@ -82,3 +82,17 @@ if 'testsettings' in os.environ['DJANGO_SETTINGS_MODULE']:
def save(self, *args, **kwargs):
self.slug = uuslug(self.name, instance=self, start_no=2, max_length=17, word_boundary=False, separator='_')
super(TruncatedSlugDifferentSeparator, self).save(*args, **kwargs)
class SmallSlug(models.Model):
"""
The slug by generated by uuslug is bigger than the field max_length
"""
name = models.CharField(max_length=20)
slug = models.CharField(max_length=10)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
self.slug = uuslug(self.name, instance=self, max_length=20)
super(SmallSlug, self).save(*args, **kwargs)

View file

@ -8,7 +8,8 @@ from django.test import TestCase
from uuslug import slugify
from uuslug.models import (CoolSlug, AnotherSlug, TruncatedSlug,
SmartTruncatedSlug, SmartTruncatedExactWordBoundrySlug,
CoolSlugDifferentSeparator, TruncatedSlugDifferentSeparator)
CoolSlugDifferentSeparator, TruncatedSlugDifferentSeparator,
SmallSlug)
class SlugUnicodeTestCase(TestCase):
@ -218,3 +219,29 @@ class SlugUniqueDifferentSeparatorTestCase(TestCase):
obj = TruncatedSlugDifferentSeparator.objects.create(name=name)
self.assertEqual(obj.slug, "jaja_lol_mememe_3") # 17 is max_length
class SlugMaxLengthTestCase(TestCase):
"""Tests for Slug - Max length minor than field length"""
def test_manager(self):
name = "john" * 51
with self.assertNumQueries(2):
obj = CoolSlug.objects.create(name=name)
self.assertEqual(obj.slug, name[:200])
with self.assertNumQueries(3):
obj = CoolSlug.objects.create(name=name)
self.assertEqual(obj.slug, name[:198] + "-1")
def test_max_length_bigger_than_field_slug(self):
name = 'jaja---lol-méméméoo--a-méméméoo'
obj = SmallSlug.objects.create(name=name)
# 10 is field max_length, 20 is uuslug function max_length
self.assertEqual(obj.slug, "jaja-lol-m")
# 10 is field max_length, 20 is uuslug function max_length
obj = SmallSlug.objects.create(name=name)
self.assertEqual(obj.slug, "jaja-lol-1")

View file

@ -33,6 +33,11 @@ def uuslug(s, instance, entities=True, decimal=True, hexadecimal=True,
if instance.pk:
queryset = queryset.exclude(pk=instance.pk)
# The slug max_length cannot be bigger than the max length of the field
slug_field_max_length = instance._meta.get_field(slug_field).max_length
if not max_length or max_length > slug_field_max_length:
max_length = slug_field_max_length
slug = slugify(s, entities=entities, decimal=decimal, hexadecimal=hexadecimal,
max_length=max_length, word_boundary=word_boundary, separator=separator,
save_order=save_order)