Skip to content

Commit 2aab63d

Browse files
committed
impruved code ValidationError compatible with Django (encode#8077)
1 parent 36bf34d commit 2aab63d

File tree

2 files changed

+14
-14
lines changed

2 files changed

+14
-14
lines changed

rest_framework/exceptions.py

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -141,29 +141,22 @@ class ValidationError(APIException):
141141
status_code = status.HTTP_400_BAD_REQUEST
142142
default_detail = _('Invalid input.')
143143
default_code = 'invalid'
144+
default_params = {}
144145

145146
def __init__(self, detail=None, code=None, params=None):
146147
if detail is None:
147148
detail = self.default_detail
148149
if code is None:
149150
code = self.default_code
151+
if params is None:
152+
params = self.default_params
150153

151154
# For validation failures, we may collect many errors together,
152155
# so the details should always be coerced to a list if not already.
153-
if isinstance(detail, tuple):
154-
detail_list = list()
155-
if params is not None:
156-
for msg in detail:
157-
detail_list.append(msg % params)
158-
detail = detail_list
159-
else:
160-
detail = list(detail)
161-
elif not isinstance(detail, dict) and not isinstance(detail, list):
162-
if params is not None:
156+
if isinstance(detail, tuple) or isinstance(detail, list):
157+
detail = [msg % params for msg in detail]
158+
elif not isinstance(detail, dict):
163159
detail = [detail % params]
164-
else:
165-
detail = [detail]
166-
167160
self.detail = _get_error_details(detail, code)
168161

169162

tests/test_validation_error.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -121,4 +121,11 @@ def test_validation_error_details_tuple(self):
121121
assert isinstance(error.detail, list)
122122
assert len(error.detail) == 2
123123
assert str(error.detail[0]) == 'Invalid value: 42'
124-
assert str(error.detail[1]) == 'Invalid value: 43'
124+
assert str(error.detail[1]) == 'Invalid value: 43'
125+
126+
def test_validation_error_details_list(self):
127+
error = ValidationError(detail=['Invalid value: %(value1)s', 'Invalid value: %(value2)s'], params={'value1': '42', 'value2':'43'})
128+
assert isinstance(error.detail, list)
129+
assert len(error.detail) == 2
130+
assert str(error.detail[0]) == 'Invalid value: 42'
131+
assert str(error.detail[1]) == 'Invalid value: 43'

0 commit comments

Comments
 (0)