#31020: Disabled ModelChoiceField produces an error in to_python
----------------------------------------+------------------------
               Reporter:  John Supplee  |          Owner:  nobody
                   Type:  Bug           |         Status:  new
              Component:  Forms         |        Version:  2.2
               Severity:  Normal        |       Keywords:
           Triage Stage:  Unreviewed    |      Has patch:  0
    Needs documentation:  0             |    Needs tests:  0
Patch needs improvement:  0             |  Easy pickings:  0
                  UI/UX:  0             |
----------------------------------------+------------------------
 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
 }}}

-- 
Ticket URL: <https://code.djangoproject.com/ticket/31020>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/052.070f8a9ad559faba8f633c6da78a0413%40djangoproject.com.

Reply via email to