Commits

Andy Mikhailenko committed a26b998 Merge

Merged in caioariede/django-autoslug/accept_nullables (pull request #4)

Allows blank/null slugs

  • Participants
  • Parent commits bb8ff86, 6ddad2a

Comments (0)

Files changed (2)

autoslug/fields.py

         if self.always_update or (self.populate_from and not value):
             value = utils.get_prepopulated_value(self, instance)
 
-            if __debug__ and not value:
+            if __debug__ and not value and not self.blank:
                 print 'Failed to populate slug %s.%s from %s' % \
                     (instance._meta.object_name, self.name, self.populate_from)
 
-        slug = self.slugify(value)
+        if value:
+            slug = self.slugify(value)
+        else:
+            slug = None
 
-        if not slug:
-            # no incoming value,  use model name
-            slug = instance._meta.module_name
+            if not self.blank:
+                slug = instance._meta.module_name
+            elif not self.null:
+                slug = ''
 
-        assert slug, 'slug is defined before trying to ensure uniqueness'
+        if not self.blank:
+            assert slug, 'slug is defined before trying to ensure uniqueness'
 
-        slug = utils.crop_slug(self, slug)
+        if slug:
+            slug = utils.crop_slug(self, slug)
 
-        # ensure the slug is unique (if required)
-        if self.unique or self.unique_with:
-            slug = utils.generate_unique_slug(self, instance, slug, manager)
+            # ensure the slug is unique (if required)
+            if self.unique or self.unique_with:
+                slug = utils.generate_unique_slug(self, instance, slug, manager)
 
-        assert slug, 'value is filled before saving'
+            assert slug, 'value is filled before saving'
 
         # make the updated slug available as instance attribute
         setattr(instance, self.name, slug)

autoslug/tests.py

     slug = AutoSlugField(populate_from=lambda instance: u'the %s' % instance.name)
 
 
+class ModelWithNullable(Model):
+    """
+    >>> a = ModelWithNullable.objects.create(name=None)
+    >>> a.slug is None
+    True
+    >>> a.slug == ''
+    False
+    """
+    name = CharField(max_length=200, blank=True, null=True)
+    slug = AutoSlugField(populate_from='name', blank=True, null=True)
+
+
+class ModelWithBlank(Model):
+    """
+    >>> a = ModelWithBlank.objects.create(name=None)
+    >>> a.slug is None
+    False
+    >>> a.slug == ''
+    True
+    """
+    name = CharField(max_length=200, blank=True, null=True)
+    slug = AutoSlugField(populate_from='name', blank=True)
+
+
 class ModelWithCallableAttr(Model):
     """
     >>> a = ModelWithCallableAttr.objects.create(name='albatross')