Skip to content

Commit f0fd411

Browse files
committed
Fixed #36201 -- Fixed ModelChoiceField/ModelMultipleChoiceField.clean() to catch ValidationError from queryset operations.
1 parent 5d13745 commit f0fd411

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

django/forms/models.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1562,7 +1562,12 @@ def to_python(self, value):
15621562
if isinstance(value, self.queryset.model):
15631563
value = getattr(value, key)
15641564
value = self.queryset.get(**{key: value})
1565-
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
1565+
except (
1566+
ValueError,
1567+
TypeError,
1568+
ValidationError,
1569+
self.queryset.model.DoesNotExist,
1570+
):
15661571
raise ValidationError(
15671572
self.error_messages["invalid_choice"],
15681573
code="invalid_choice",
@@ -1640,7 +1645,7 @@ def _check_values(self, value):
16401645
self.validate_no_null_characters(pk)
16411646
try:
16421647
self.queryset.filter(**{key: pk})
1643-
except (ValueError, TypeError):
1648+
except (ValueError, TypeError, ValidationError):
16441649
raise ValidationError(
16451650
self.error_messages["invalid_pk_value"],
16461651
code="invalid_pk_value",

tests/model_forms/test_uuid.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,6 @@ def test_update_save_error(self):
3030
def test_model_multiple_choice_field_uuid_pk(self):
3131
f = forms.ModelMultipleChoiceField(UUIDPK.objects.all())
3232
with self.assertRaisesMessage(
33-
ValidationError, "“invalid_uuid” is not a valid UUID."
33+
ValidationError, "“invalid_uuid” is not a valid value."
3434
):
3535
f.clean(["invalid_uuid"])

0 commit comments

Comments
 (0)