1
0
mirror of https://github.com/django/django.git synced 2025-11-07 07:15:35 +00:00

Fixed #30014 -- Fixed ModelChoiceField validation when initial value is a model instance.

Thanks Carlton Gibson for reviews.
This commit is contained in:
Etienne Chové
2019-03-13 10:02:50 +01:00
committed by Mariusz Felisiak
parent a12f9cd95a
commit e7cdb0cd7e
2 changed files with 21 additions and 0 deletions

View File

@@ -1248,6 +1248,8 @@ class ModelChoiceField(ChoiceField):
return None
try:
key = self.to_field_name or 'pk'
if isinstance(value, self.queryset.model):
value = getattr(value, key)
value = self.queryset.get(**{key: value})
except (ValueError, TypeError, self.queryset.model.DoesNotExist):
raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')