mirror of
https://github.com/encode/django-rest-framework.git
synced 2024-11-10 19:56:59 +03:00
Handle empty data with serializer (#4564)
This commit is contained in:
parent
4c9b14bd97
commit
b419970431
|
@ -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)
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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):
|
||||
|
|
Loading…
Reference in New Issue
Block a user