mirror of
https://github.com/encode/django-rest-framework.git
synced 2025-07-27 08:29:59 +03:00
impruved code ValidationError compatible with Django (#8077)
This commit is contained in:
parent
36bf34dd1b
commit
2aab63d7a5
|
@ -141,29 +141,22 @@ class ValidationError(APIException):
|
||||||
status_code = status.HTTP_400_BAD_REQUEST
|
status_code = status.HTTP_400_BAD_REQUEST
|
||||||
default_detail = _('Invalid input.')
|
default_detail = _('Invalid input.')
|
||||||
default_code = 'invalid'
|
default_code = 'invalid'
|
||||||
|
default_params = {}
|
||||||
|
|
||||||
def __init__(self, detail=None, code=None, params=None):
|
def __init__(self, detail=None, code=None, params=None):
|
||||||
if detail is None:
|
if detail is None:
|
||||||
detail = self.default_detail
|
detail = self.default_detail
|
||||||
if code is None:
|
if code is None:
|
||||||
code = self.default_code
|
code = self.default_code
|
||||||
|
if params is None:
|
||||||
|
params = self.default_params
|
||||||
|
|
||||||
# For validation failures, we may collect many errors together,
|
# For validation failures, we may collect many errors together,
|
||||||
# so the details should always be coerced to a list if not already.
|
# so the details should always be coerced to a list if not already.
|
||||||
if isinstance(detail, tuple):
|
if isinstance(detail, tuple) or isinstance(detail, list):
|
||||||
detail_list = list()
|
detail = [msg % params for msg in detail]
|
||||||
if params is not None:
|
elif not isinstance(detail, dict):
|
||||||
for msg in detail:
|
|
||||||
detail_list.append(msg % params)
|
|
||||||
detail = detail_list
|
|
||||||
else:
|
|
||||||
detail = list(detail)
|
|
||||||
elif not isinstance(detail, dict) and not isinstance(detail, list):
|
|
||||||
if params is not None:
|
|
||||||
detail = [detail % params]
|
detail = [detail % params]
|
||||||
else:
|
|
||||||
detail = [detail]
|
|
||||||
|
|
||||||
self.detail = _get_error_details(detail, code)
|
self.detail = _get_error_details(detail, code)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -121,4 +121,11 @@ class TestvalidationErrorWithDjangoStyle(TestCase):
|
||||||
assert isinstance(error.detail, list)
|
assert isinstance(error.detail, list)
|
||||||
assert len(error.detail) == 2
|
assert len(error.detail) == 2
|
||||||
assert str(error.detail[0]) == 'Invalid value: 42'
|
assert str(error.detail[0]) == 'Invalid value: 42'
|
||||||
assert str(error.detail[1]) == 'Invalid value: 43'
|
assert str(error.detail[1]) == 'Invalid value: 43'
|
||||||
|
|
||||||
|
def test_validation_error_details_list(self):
|
||||||
|
error = ValidationError(detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s'], params={'value1': '42', 'value2':'43'})
|
||||||
|
assert isinstance(error.detail, list)
|
||||||
|
assert len(error.detail) == 2
|
||||||
|
assert str(error.detail[0]) == 'Invalid value: 42'
|
||||||
|
assert str(error.detail[1]) == 'Invalid value: 43'
|
||||||
|
|
Loading…
Reference in New Issue
Block a user