Opened 17 years ago

Closed 13 years ago

Last modified 13 years ago

#5327 closed (fixed)

ModelChoiceField and ChoiceField clean methods behave differently

Reported by: danielrubio Owned by: Philippe Raoult
Component: Documentation Version: dev
Severity: Keywords: ChoiceField clean method id
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description (last modified by Malcolm Tredinnick)

Using both ChoiceField and ModelChoiceField, I discovered a bug in ChoiceField clean method ( or a discrepancy in behaviour)

ModelChoiceField seems to be working as expected, when I call the clean method in a template like so: form.clean.city , I get the city name(e.g New York), or what would be string inside the tag <select id="5"> New York </select>

This behaviour is different if the values are inside a ChoiceField, if I use the following in the template: form.clean.city, I get the city id (e.g 5 ), not the expected string or behaviour as using ModelChoiceField.

[NOTE: Not calling the clean field, in either !ChoiceField or !ModelChoiceField works identcally, generating a select list ]

I modified the fields.py file in django/newforms, the clean method on the ChoiceField class[line 466], would now read:

 def clean(self, value):
        """
        Validates that the input is in self.choices.
        """
        value = super(ChoiceField, self).clean(value)
        if value in EMPTY_VALUES:
            value = u''
        value = smart_unicode(value)
        if value == u'':
            return value
        valid_values = set([smart_unicode(k) for k, v in self.choices])
        if value not in valid_values:
            raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.'))
        else:
            value = self._choices[int(value)][1]
        return value

Only modification is the 'else' at the end, which would assign the value to the actual string.


Attachments (1)

5327.diff (1.6 KB ) - added by Philippe Raoult 17 years ago.
clarification of the docs concerning ModelChoices

Download all attachments as: .zip

Change History (14)

comment:1 by danielrubio, 17 years ago

Did some more testing, the previous fix assumed the option keys were in order 1,2,3,4,5,6,7,8,9.etc.. I had a list ordered by name, and the previous code obviosuly gave the wrong key value. The following snippet will fix this.

if value not in valid_values:

raise ValidationError(ugettext(u'Select a valid choice. That choice is not one of the available choices.'))

else:

for k, v in self.choices:

if(smart_unicode(k) == value):

return smart_unicode(v)

comment:2 by Philippe Raoult, 17 years ago

Needs documentation: set
Owner: changed from nobody to Philippe Raoult
Triage Stage: UnreviewedDesign decision needed

Logically the model choicefield should be able to return either an object or just its id, but that should be more explicit in the docs (it is not explicitely listed in the FormField list). Also, the ChoiceField doc doesn't say if the first or second member of the choice tuple is used as the normalized value.

by Philippe Raoult, 17 years ago

Attachment: 5327.diff added

clarification of the docs concerning ModelChoices

comment:3 by Philippe Raoult, 17 years ago

Has patch: set
Needs documentation: unset
Status: newassigned
Triage Stage: Design decision neededReady for checkin

comment:4 by Malcolm Tredinnick, 17 years ago

Description: modified (diff)

(fixed description formatting)

comment:5 by Malcolm Tredinnick, 17 years ago

Summary: ChoiceField clean methodModelChoiceField and ChoiceField clean methods behave differently

We should resolve the inconsistency here, I suspect. My gut feeling is that cleaning to the id value is more correct, because that is what you would assign to a field that had "choices" as an option. But whichever way we go, I'm not too comfortable with the inconsistency. ModelChoiceField subclasses ChoiceField, so it shouldn't behave wildly differently.

comment:6 by Malcolm Tredinnick, 17 years ago

Triage Stage: Ready for checkinDesign decision needed

comment:7 by Philippe Raoult, 17 years ago

ModelChoiceField will NOT return a name, it will return the object associated with the id you selected. The only difference with a ChoiceField is that ModelChoiceField will resolve the object from the id in the queryset, which is to be expected given the field name. There is no inconsistency here, and the patch only clarifies the current documentation.

comment:8 by Ramiro Morales, 17 years ago

From what I idnerstand from the description, Daniel isn't reporting about ModelChoiceField but about what component of the relevant choices member the clean method of ChoiceField is returning.

Could this be then related to #5481?

comment:9 by Robert Coup, 17 years ago

#5481 for fixes ChoiceField choices keys in the general case.

IMHO PhiR's doc patch is correct:

  • ChoiceField normalises to the key, that is the generally expected behaviour - otherwise you get a translated string or something else back.
  • ModelChoiceField normalises to the model object. It will use the queryset to initialize the keys/strings and then returns back the model object from clean()

I'd suggest that using form.cleaned_data.city in a template isn't the best way to get a choice label. It would be relatively easy to create a filter or a tag to do it:

@register.simple_tag
def choice_value_label(form, field_name):
   return dict(form.fields[field_name].choices)[form.cleaned_data[field_name]

<span>{% choice_value form "city" %}</span>

comment:10 by Russell Keith-Magee, 14 years ago

Component: FormsDocumentation
Triage Stage: Design decision neededAccepted

Accepted that the documentation is what needs to be fixed here.

comment:11 by Gabriel Hurley, 13 years ago

Most of this patch (and ticket) was taken care of years ago. I'll merge in the last tiny bits and call it done.

comment:12 by Gabriel Hurley, 13 years ago

Resolution: fixed
Status: assignedclosed

(In [14214]) Fixed #5327 -- Added standardized field information to ModelChoiceField and ModelMultipleChoiceField documentation. Thanks to danielrubio for the report and PhiR for the text.

comment:13 by Gabriel Hurley, 13 years ago

(In [14215]) [1.2.X] Fixed #5327 -- Added standardized field information to ModelChoiceField and ModelMultipleChoiceField documentation. Thanks to danielrubio for the report and PhiR for the text.

Backport of [14214] from trunk.

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