mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-08-05 04:50:12 +03:00
Merge 345bf42ce9
into ef89c15663
This commit is contained in:
commit
962d8fe5d3
|
@ -462,6 +462,42 @@ class ListSerializer(BaseSerializer):
|
|||
return html.parse_html_list(dictionary, prefix=self.field_name)
|
||||
return dictionary.get(self.field_name, empty)
|
||||
|
||||
def run_validation(self, data=empty):
|
||||
data = super(ListSerializer, self).run_validation(data)
|
||||
|
||||
try:
|
||||
data = self.validate(data)
|
||||
assert data is not None, '.validate() should return the validated data'
|
||||
except ValidationError as exc:
|
||||
if isinstance(exc.detail, dict):
|
||||
# .validate() errors may be a dict, in which case, use
|
||||
# standard {key: list of values} style.
|
||||
raise ValidationError(dict([
|
||||
(key, value if isinstance(value, list) else [value])
|
||||
for key, value in exc.detail.items()
|
||||
]))
|
||||
elif isinstance(exc.detail, list):
|
||||
raise ValidationError({
|
||||
api_settings.NON_FIELD_ERRORS_KEY: exc.detail
|
||||
})
|
||||
else:
|
||||
raise ValidationError({
|
||||
api_settings.NON_FIELD_ERRORS_KEY: [exc.detail]
|
||||
})
|
||||
except DjangoValidationError as exc:
|
||||
# Normally you should raise `serializers.ValidationError`
|
||||
# inside your codebase, but we handle Django's validation
|
||||
# exception class as well for simpler compat.
|
||||
# Eg. Calling Model.clean() explicitly inside Serializer.validate()
|
||||
raise ValidationError({
|
||||
api_settings.NON_FIELD_ERRORS_KEY: list(exc.messages)
|
||||
})
|
||||
|
||||
return data
|
||||
|
||||
def validate(self, attrs):
|
||||
return attrs
|
||||
|
||||
def to_internal_value(self, data):
|
||||
"""
|
||||
List of dicts of native values <- List of dicts of primitive datatypes.
|
||||
|
|
|
@ -272,3 +272,19 @@ class TestNestedListOfListsSerializer:
|
|||
serializer = self.Serializer(data=input_data)
|
||||
assert serializer.is_valid()
|
||||
assert serializer.validated_data == expected_output
|
||||
|
||||
|
||||
class TestListSerializerClass:
|
||||
"""Tests for a custom list_serializer_class."""
|
||||
def test_list_serializer_class_validate(self):
|
||||
class CustomListSerializer(serializers.ListSerializer):
|
||||
def validate(self, attrs):
|
||||
raise serializers.ValidationError('Non field error')
|
||||
|
||||
class TestSerializer(serializers.Serializer):
|
||||
class Meta:
|
||||
list_serializer_class = CustomListSerializer
|
||||
|
||||
serializer = TestSerializer(data=[], many=True)
|
||||
assert not serializer.is_valid()
|
||||
assert serializer.errors == {'non_field_errors': ['Non field error']}
|
||||
|
|
Loading…
Reference in New Issue
Block a user