Skip to content

Commit

Permalink
Merge pull request #3321 from tomchristie/empty-charfield-html
Browse files Browse the repository at this point in the history
Resolve empty HTML charfield behavior.
  • Loading branch information
tomchristie committed Aug 24, 2015
2 parents 9758838 + 9ac6463 commit b271946
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
6 changes: 4 additions & 2 deletions rest_framework/fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -385,8 +385,10 @@ def get_value(self, dictionary):
# 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)

Expand Down
18 changes: 17 additions & 1 deletion tests/test_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -253,14 +253,30 @@ class TestSerializer(serializers.Serializer):


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')

serializer = TestSerializer(data=QueryDict(''))
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)
Expand Down

0 comments on commit b271946

Please sign in to comment.