Ticket #9209: django-modelchoicefields-invalid-value.patch

File django-modelchoicefields-invalid-value.patch, 2.5 KB (added by hgeerts@…, 14 years ago)
  • django/forms/models.py

     
    920920    default_error_messages = {
    921921        'invalid_choice': _(u'Select a valid choice. That choice is not one of'
    922922                            u' the available choices.'),
     923        'invalid_pk_value': _(u'"%s" is not a valid value for a primary key.')
    923924    }
    924925
    925926    def __init__(self, queryset, empty_label=u"---------", cache_choices=False,
     
    984985    def to_python(self, value):
    985986        if value in EMPTY_VALUES:
    986987            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
    987991        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})
    990997        except self.queryset.model.DoesNotExist:
    991998            raise ValidationError(self.error_messages['invalid_choice'])
    992999        return value
     
    10191026            return []
    10201027        if not isinstance(value, (list, tuple)):
    10211028            raise ValidationError(self.error_messages['list'])
     1029        field = self.queryset.model._meta.pk
    10221030        for pk in value:
    10231031            try:
    1024                 self.queryset.filter(pk=pk)
    1025             except ValueError:
     1032                field.to_python(pk)
     1033            except ValidationError:
    10261034                raise ValidationError(self.error_messages['invalid_pk_value'] % pk)
    10271035        qs = self.queryset.filter(pk__in=value)
    10281036        pks = set([force_unicode(o.pk) for o in qs])
  • tests/modeltests/model_forms/models.py

     
    860860Traceback (most recent call last):
    861861...
    862862ValidationError: [u'Select a valid choice. That choice is not one of the available choices.']
     863>>> f.clean('fail')
     864Traceback (most recent call last):
     865...
     866ValidationError: [u'"fail" is not a valid value for a primary key.']
    863867>>> f.clean(3)
    864868<Category: Third>
    865869>>> f.clean(2)
Back to Top