Resolve empty HTML charfield behavior. Closes #3318.

This commit is contained in:
Tom Christie 2015-08-24 10:13:16 +01:00
parent f601c6c1c3
commit 9ac646385f
2 changed files with 21 additions and 3 deletions

View File

@ -385,8 +385,10 @@ class Field(object):
# If the field is blank, and null is a valid value then # If the field is blank, and null is a valid value then
# determine if we should use null instead. # determine if we should use null instead.
return '' if getattr(self, 'allow_blank', False) else None return '' if getattr(self, 'allow_blank', False) else None
elif ret == '' and self.default: elif ret == '' and not self.required:
return empty # If the field is blank, and emptyness is valid then
# determine if we should use emptyness instead.
return '' if getattr(self, 'allow_blank', False) else empty
return ret return ret
return dictionary.get(self.field_name, empty) return dictionary.get(self.field_name, empty)

View File

@ -253,7 +253,7 @@ class TestBooleanHTMLInput:
class TestHTMLInput: class TestHTMLInput:
def test_empty_html_charfield(self): def test_empty_html_charfield_with_default(self):
class TestSerializer(serializers.Serializer): class TestSerializer(serializers.Serializer):
message = serializers.CharField(default='happy') message = serializers.CharField(default='happy')
@ -261,6 +261,22 @@ class TestHTMLInput:
assert serializer.is_valid() assert serializer.is_valid()
assert serializer.validated_data == {'message': 'happy'} assert serializer.validated_data == {'message': 'happy'}
def test_empty_html_charfield_without_default(self):
class TestSerializer(serializers.Serializer):
message = serializers.CharField(allow_blank=True)
serializer = TestSerializer(data=QueryDict('message='))
assert serializer.is_valid()
assert serializer.validated_data == {'message': ''}
def test_empty_html_charfield_without_default_not_required(self):
class TestSerializer(serializers.Serializer):
message = serializers.CharField(allow_blank=True, required=False)
serializer = TestSerializer(data=QueryDict('message='))
assert serializer.is_valid()
assert serializer.validated_data == {'message': ''}
def test_empty_html_integerfield(self): def test_empty_html_integerfield(self):
class TestSerializer(serializers.Serializer): class TestSerializer(serializers.Serializer):
message = serializers.IntegerField(default=123) message = serializers.IntegerField(default=123)