diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9d707c9b5..5955fa3f1 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -475,8 +475,12 @@ class CharField(WritableField): if isinstance(value, six.string_types): return value - if value is None and not self.allow_none: - return '' + 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) diff --git a/tests/test_fields.py b/tests/test_fields.py index 094ac1eb0..b8c9954ea 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -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