Skip to content

Commit 04158e1

Browse files
committed
Merge pull request #3513 from pattisdr/feature/ListField_needs_to_enforce_list
ListField does not enforce that input is a list
2 parents 75a63c2 + 3ddbf92 commit 04158e1

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

rest_framework/fields.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1461,7 +1461,7 @@ def to_internal_value(self, data):
14611461
"""
14621462
if html.is_html_input(data):
14631463
data = html.parse_html_list(data)
1464-
if isinstance(data, type('')) or not hasattr(data, '__iter__'):
1464+
if isinstance(data, type('')) or isinstance(data, collections.Mapping) or not hasattr(data, '__iter__'):
14651465
self.fail('not_a_list', input_type=type(data).__name__)
14661466
if not self.allow_empty and len(data) == 0:
14671467
self.fail('empty')

tests/test_fields.py

+10-1
Original file line numberDiff line numberDiff line change
@@ -1437,7 +1437,8 @@ class TestListField(FieldValues):
14371437
]
14381438
invalid_inputs = [
14391439
('not a list', ['Expected a list of items but got type "str".']),
1440-
([1, 2, 'error'], ['A valid integer is required.'])
1440+
([1, 2, 'error'], ['A valid integer is required.']),
1441+
({'one': 'two'}, ['Expected a list of items but got type "dict".'])
14411442
]
14421443
outputs = [
14431444
([1, 2, 3], [1, 2, 3]),
@@ -1454,6 +1455,14 @@ def test_no_source_on_child(self):
14541455
"Remove `source=` from the field declaration."
14551456
)
14561457

1458+
def test_collection_types_are_invalid_input(self):
1459+
field = serializers.ListField(child=serializers.CharField())
1460+
input_value = ({'one': 'two'})
1461+
1462+
with pytest.raises(serializers.ValidationError) as exc_info:
1463+
field.to_internal_value(input_value)
1464+
assert exc_info.value.detail == ['Expected a list of items but got type "dict".']
1465+
14571466

14581467
class TestEmptyListField(FieldValues):
14591468
"""

0 commit comments

Comments
 (0)