From b4199704316bd2d67281cbc3cf946eab9bded407 Mon Sep 17 00:00:00 2001 From: Tom Christie Date: Wed, 12 Oct 2016 10:47:17 +0100 Subject: [PATCH] Handle empty data with serializer (#4564) --- rest_framework/serializers.py | 10 ++++++++++ tests/test_serializer.py | 6 ++++++ tests/test_serializer_nested.py | 6 ++++++ 3 files changed, 22 insertions(+) diff --git a/rest_framework/serializers.py b/rest_framework/serializers.py index a6ed7d87e..02c21da15 100644 --- a/rest_framework/serializers.py +++ b/rest_framework/serializers.py @@ -507,6 +507,11 @@ class Serializer(BaseSerializer): @property def errors(self): ret = super(Serializer, self).errors + if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null': + # Edge case. Provide a more descriptive error than + # "this field may not be null", when no data is passed. + detail = ErrorDetail('No data provided', code='null') + ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} return ReturnDict(ret, serializer=self) @@ -700,6 +705,11 @@ class ListSerializer(BaseSerializer): @property def errors(self): ret = super(ListSerializer, self).errors + if isinstance(ret, list) and len(ret) == 1 and ret[0].code == 'null': + # Edge case. Provide a more descriptive error than + # "this field may not be null", when no data is passed. + detail = ErrorDetail('No data provided', code='null') + ret = {api_settings.NON_FIELD_ERRORS_KEY: [detail]} if isinstance(ret, dict): return ReturnDict(ret, serializer=self) return ReturnList(ret, serializer=self) diff --git a/tests/test_serializer.py b/tests/test_serializer.py index bd9ef9500..a2817f6a4 100644 --- a/tests/test_serializer.py +++ b/tests/test_serializer.py @@ -62,6 +62,12 @@ class TestSerializer: with pytest.raises(AssertionError): serializer.save() + def test_validate_none_data(self): + data = None + serializer = self.Serializer(data=data) + assert not serializer.is_valid() + assert serializer.errors == {'non_field_errors': ['No data provided']} + class TestValidateMethod: def test_non_field_error_validate_method(self): diff --git a/tests/test_serializer_nested.py b/tests/test_serializer_nested.py index 133600399..efb671918 100644 --- a/tests/test_serializer_nested.py +++ b/tests/test_serializer_nested.py @@ -41,6 +41,12 @@ class TestNestedSerializer: serializer = self.Serializer() assert serializer.data == expected_data + def test_nested_serialize_no_data(self): + data = None + serializer = self.Serializer(data=data) + assert not serializer.is_valid() + assert serializer.errors == {'non_field_errors': ['No data provided']} + class TestNotRequiredNestedSerializer: def setup(self):