Ticket #9209: django-modelchoicefields-invalid-value.patch
File django-modelchoicefields-invalid-value.patch, 2.5 KB (added by , 14 years ago) |
---|
-
django/forms/models.py
920 920 default_error_messages = { 921 921 'invalid_choice': _(u'Select a valid choice. That choice is not one of' 922 922 u' the available choices.'), 923 'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.') 923 924 } 924 925 925 926 def __init__(self, queryset, empty_label=u"---------", cache_choices=False, … … 984 985 def to_python(self, value): 985 986 if value in EMPTY_VALUES: 986 987 return None 988 opts = self.queryset.model._meta 989 # can raise FieldDoesNotExist which is a programming error so we don't catch it 990 field = self.to_field_name and opts.get_field(self.to_field_name) or opts.pk 987 991 try: 988 key = self.to_field_name or 'pk' 989 value = self.queryset.get(**{key: value}) 992 value = field.to_python(value) 993 except ValidationError: 994 raise ValidationError(self.error_messages['invalid_pk_value'] % value) 995 try: 996 value = self.queryset.get(**{field.name: value}) 990 997 except self.queryset.model.DoesNotExist: 991 998 raise ValidationError(self.error_messages['invalid_choice']) 992 999 return value … … 1019 1026 return [] 1020 1027 if not isinstance(value, (list, tuple)): 1021 1028 raise ValidationError(self.error_messages['list']) 1029 field = self.queryset.model._meta.pk 1022 1030 for pk in value: 1023 1031 try: 1024 self.queryset.filter(pk=pk)1025 except Val ueError:1032 field.to_python(pk) 1033 except ValidationError: 1026 1034 raise ValidationError(self.error_messages['invalid_pk_value'] % pk) 1027 1035 qs = self.queryset.filter(pk__in=value) 1028 1036 pks = set([force_unicode(o.pk) for o in qs]) -
tests/modeltests/model_forms/models.py
860 860 Traceback (most recent call last): 861 861 ... 862 862 ValidationError: [u'Select a valid choice. That choice is not one of the available choices.'] 863 >>> f.clean('fail') 864 Traceback (most recent call last): 865 ... 866 ValidationError: [u'"fail" is not a valid value for a primary key.'] 863 867 >>> f.clean(3) 864 868 <Category: Third> 865 869 >>> f.clean(2)