Skip to content

Commit

Permalink
Merge pull request encode#1834 from piotrjakimiak/master
Browse files Browse the repository at this point in the history
Fix returning None when allow_none is True in CharField
  • Loading branch information
tomchristie committed Sep 5, 2014
2 parents 4207d44 + cb3cc00 commit 2b47c6b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 2 deletions.
8 changes: 6 additions & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -475,8 +475,12 @@ def from_native(self, value):
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)

Expand Down
12 changes: 12 additions & 0 deletions tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -1004,6 +1004,18 @@ class BooleanRequiredSerializer(serializers.Serializer):
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
Expand Down

0 comments on commit 2b47c6b

Please sign in to comment.