Fixed #26743 -- Fixed UnboundLocalError crash when deserializing m2m fields and value isn't iterable.

This commit is contained in:
Baptiste Mispelon 2019-12-11 19:36:57 +01:00 committed by Mariusz Felisiak
parent 3fe5d0128b
commit 738e9e615d
2 changed files with 19 additions and 1 deletions

View File

@ -282,9 +282,13 @@ def deserialize_m2m_values(field, field_value, using, handle_forward_references)
def m2m_convert(v):
return model._meta.pk.to_python(v)
try:
pks_iter = iter(field_value)
except TypeError as e:
raise M2MDeserializationError(e, field_value)
try:
values = []
for pk in field_value:
for pk in pks_iter:
values.append(m2m_convert(pk))
return values
except Exception as e:

View File

@ -252,6 +252,20 @@ class JsonSerializerTestCase(SerializersTestBase, TestCase):
for obj in serializers.deserialize('json', test_string, ignore=False):
obj.save()
def test_helpful_error_message_for_many2many_not_iterable(self):
"""
Not iterable many-to-many field value throws a helpful error message.
"""
test_string = """[{
"pk": 1,
"model": "serializers.m2mdata",
"fields": {"data": null}
}]"""
expected = "(serializers.m2mdata:pk=1) field_value was 'None'"
with self.assertRaisesMessage(DeserializationError, expected):
next(serializers.deserialize('json', test_string, ignore=False))
class JsonSerializerTransactionTestCase(SerializersTransactionTestBase, TransactionTestCase):
serializer_name = "json"