diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 10a310280..faf41e7a0 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -385,8 +385,10 @@ class Field(object): # If the field is blank, and null is a valid value then # determine if we should use null instead. return '' if getattr(self, 'allow_blank', False) else None - elif ret == '' and self.default: - return empty + elif ret == '' and not self.required: + # 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 dictionary.get(self.field_name, empty) diff --git a/tests/test_fields.py b/tests/test_fields.py index 58c1c9243..8065c8260 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -253,7 +253,7 @@ class TestBooleanHTMLInput: class TestHTMLInput: - def test_empty_html_charfield(self): + def test_empty_html_charfield_with_default(self): class TestSerializer(serializers.Serializer): message = serializers.CharField(default='happy') @@ -261,6 +261,22 @@ class TestHTMLInput: assert serializer.is_valid() 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): class TestSerializer(serializers.Serializer): message = serializers.IntegerField(default=123)