Skip to content

Commit 95ba2ac

Browse files
committed
Handle tuples same as lists in ValidationError detail context
1 parent 96993d8 commit 95ba2ac

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

rest_framework/exceptions.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def _get_error_details(data, default_code=None):
2020
Descend into a nested data structure, forcing any
2121
lazy translation strings or strings into `ErrorDetail`.
2222
"""
23-
if isinstance(data, list):
23+
if isinstance(data, (list, tuple)):
2424
ret = [
2525
_get_error_details(item, default_code) for item in data
2626
]
@@ -150,7 +150,9 @@ def __init__(self, detail=None, code=None):
150150

151151
# For validation failures, we may collect many errors together,
152152
# so the details should always be coerced to a list if not already.
153-
if not isinstance(detail, dict) and not isinstance(detail, list):
153+
if isinstance(detail, tuple):
154+
detail = list(detail)
155+
elif not isinstance(detail, dict) and not isinstance(detail, list):
154156
detail = [detail]
155157

156158
self.detail = _get_error_details(detail, code)

tests/test_validation_error.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from rest_framework import serializers, status
44
from rest_framework.decorators import api_view
5+
from rest_framework.exceptions import ValidationError
56
from rest_framework.response import Response
67
from rest_framework.settings import api_settings
78
from rest_framework.test import APIRequestFactory
@@ -99,3 +100,12 @@ def test_function_based_view_exception_handler(self):
99100
response = view(request)
100101
assert response.status_code == status.HTTP_400_BAD_REQUEST
101102
assert response.data == self.expected_response_data
103+
104+
105+
class TestValidationErrorConvertsTuplesToLists(TestCase):
106+
def test_validation_error_details(self):
107+
error = ValidationError(detail=('message1', 'message2'))
108+
assert isinstance(error.detail, list)
109+
assert len(error.detail) == 2
110+
error.detail[0].string == 'message1'
111+
error.detail[1].string == 'message2'

0 commit comments

Comments
 (0)