Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#31020 closed Bug (duplicate)

Disabled ModelChoiceField produces an error in to_python

Reported by: John Supplee Owned by: nobody
Component: Forms Version: 2.2
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When a form with a disabled ModelChoiceField with an initial value is validated it produces an error.

It seems that disabled fields go through the data cleaning process and the .to_python(value) method is called. For most fields that is not a problem as the value passed to the to_python() method is massaged and returned. In the case of a ModelChoiceField the initial value passed is a Model object. This causes to_python() to throw a ValidationError of:

Select a valid choice. That choice is not one of the available choices.

It seems that to_python() is expecting a text value from a POST.

ModelChoiceField.to_python() needs to be modified to return the passed value if the field is disabled.

The below code is from 2.2.7 with the addition of two new lines at the beginning of the method.

    def to_python(self, value):
        if self.disabled:
            return value
        if value in self.empty_values:
            return None
        try:
            key = self.to_field_name or 'pk'
            value = self.queryset.get(**{key: value})
        except (ValueError, TypeError, self.queryset.model.DoesNotExist):
            raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice')
        return value

Change History (3)

comment:1 by Carlton Gibson, 5 years ago

Resolution: duplicate
Status: newclosed

Duplicate of #30014. (Fixed in Django 3.0.)

comment:2 by John Supplee, 5 years ago

Why can't this bug be fixed in Django 2?

comment:3 by Carlton Gibson, 5 years ago

Note: See TracTickets for help on using tickets.
Back to Top