Caio Ariede avatar Caio Ariede committed 6ddad2a

Added tests and made some refactoring

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 and not self.blank:
-            # 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 = ''
 
         if not self.blank:
             assert slug, 'slug is defined before trying to ensure uniqueness'
 
             assert slug, 'value is filled before saving'
 
-        elif self.null:
-            # If the field is nullable
-            slug = None
-
         # 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')
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.