diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 9d707c9b5..8e15345da 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 explicitly because smart_text(None) == 'None'. See #1834 for details + return None return smart_text(value) diff --git a/tests/test_fields.py b/tests/test_fields.py index 094ac1eb0..0ddbe48b5 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -1004,6 +1004,18 @@ class BooleanField(TestCase): self.assertFalse(BooleanRequiredSerializer(data={}).is_valid()) +class ModelCharField(TestCase): + """ + Tests for CharField + """ + def test_none_serializing(self): + class CharFieldSerializer(serializers.Serializer): + char = serializers.CharField(allow_none=True, required=False) + serializer = CharFieldSerializer(data={'char': None}) + self.assertTrue(serializer.is_valid()) + self.assertIsNone(serializer.object['char']) + + class SerializerMethodFieldTest(TestCase): """ Tests for the SerializerMethodField field_to_native() behavior