1
0
mirror of https://github.com/django/django.git synced 2025-03-12 18:30:48 +00:00

Fixed #36201 -- Caught ValidationError in ModelChoiceField/ModelMultipleChoiceField.clean().

Signed-off-by: saJaeHyukc <wogur981208@gmail.com>
This commit is contained in:
saJaeHyukc 2025-03-09 00:42:16 +09:00 committed by Sarah Boyce
parent 9120a19c4e
commit f480d5d3ed
2 changed files with 17 additions and 3 deletions

View File

@ -1562,7 +1562,12 @@ class ModelChoiceField(ChoiceField):
if isinstance(value, self.queryset.model):
value = getattr(value, key)
value = self.queryset.get(**{key: value})
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
except (
ValueError,
TypeError,
self.queryset.model.DoesNotExist,
ValidationError,
):
raise ValidationError(
self.error_messages["invalid_choice"],
code="invalid_choice",
@ -1640,7 +1645,7 @@ class ModelMultipleChoiceField(ModelChoiceField):
self.validate_no_null_characters(pk)
try:
self.queryset.filter(**{key: pk})
except (ValueError, TypeError):
except (ValueError, TypeError, ValidationError):
raise ValidationError(
self.error_messages["invalid_pk_value"],
code="invalid_pk_value",

View File

@ -30,6 +30,15 @@ class ModelFormBaseTest(TestCase):
def test_model_multiple_choice_field_uuid_pk(self):
f = forms.ModelMultipleChoiceField(UUIDPK.objects.all())
with self.assertRaisesMessage(
ValidationError, "“invalid_uuid” is not a valid UUID."
ValidationError, "“invalid_uuid” is not a valid value."
):
f.clean(["invalid_uuid"])
def test_model_choice_invalid_pk_value_error_messages(self):
f = forms.ModelChoiceField(UUIDPK.objects.all())
with self.assertRaisesMessage(
ValidationError,
"['Select a valid choice. "
"That choice is not one of the available choices.']",
):
f.clean("invalid")