Fix returning None when allow_none is True in CharField

This commit is contained in:
Piotr Jakimiak 2014-09-05 11:08:34 +02:00
parent 2e632e5af2
commit d9633c6817
2 changed files with 24 additions and 2 deletions

View File

@ -475,8 +475,12 @@ class CharField(WritableField):
if isinstance(value, six.string_types):
return value
if value is None and not self.allow_none:
if value is None:
if not self.allow_none:
return ''
else:
# return None implicity because smart_text(None) == 'None'
return None
return smart_text(value)

View File

@ -54,6 +54,10 @@ class ChoiceFieldModel(models.Model):
choice = models.CharField(choices=SAMPLE_CHOICES, blank=True, max_length=255)
class NullableCharFieldModel(models.Model):
char = models.CharField(null=True, blank=True, max_length=4)
class ChoiceFieldModelSerializer(serializers.ModelSerializer):
class Meta:
model = ChoiceFieldModel
@ -1004,6 +1008,20 @@ class BooleanField(TestCase):
self.assertFalse(BooleanRequiredSerializer(data={}).is_valid())
class ModelCharField(TestCase):
"""
Tests for CharField
"""
def test_none_serializing(self):
class CharFieldSerializer(serializers.ModelSerializer):
class Meta:
model = NullableCharFieldModel
serializer = CharFieldSerializer(data={'char': None})
self.assertTrue(serializer.fields['char'].allow_none)
self.assertTrue(serializer.is_valid())
self.assertIsNone(serializer.data['char'])
class SerializerMethodFieldTest(TestCase):
"""
Tests for the SerializerMethodField field_to_native() behavior