Opened 5 years ago

Closed 4 years ago

#13942 closed (invalid)

ModelChoiceField fix to_field_name fix

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

Description

line 989 in http://code.djangoproject.com/browser/django/trunk/django/forms/models.py

ModelChoiceField

986 def to_python(self, value):
985 if value in EMPTY_VALUES:
986 return None
987 try:
988 key = self.to_field_name or 'pk'
989 value = self.queryset.get({key: value})
990 except self.queryset.model.DoesNotExist:
991 raise ValidationError(self.error_messagesinvalid_choice?)
992 return value

If you supply a to_field_name argument then the value that would be used from that field name is replaced here.
Suggest replacing this with dummy object variable ...

989 object = self.queryset.get({key: value})

... so you get back the original field value, then this works for generating choices with different option values to labels.

Change History (1)

comment:1 in reply to: ↑ description Changed 4 years ago by SmileyChris

  • Has patch unset
  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

Replying to edcrewe:

> line 989 in http://code.djangoproject.com/browser/django/trunk/django/forms/models.py
> 
> ModelChoiceField
> 
> 986    def to_python(self, value):
> 985 	        if value in EMPTY_VALUES:</pre>
> 986 	            return None
> 987 	        try:
> 988 	            key = self.to_field_name or 'pk'
> 989 	            value = self.queryset.get(**{key: value})
> 990 	        except self.queryset.model.DoesNotExist:
> 991 	            raise ValidationError(self.error_messages['invalid_choice'])
> 992 	        return value
> 
> If you supply a to_field_name argument then the value that would be used from that field name is replaced here.
> Suggest replacing this with dummy object variable ...
> 
> 989 object = self.queryset.get(**{key: value})
> 
> ... so you get back the original field value, then this works for generating choices with different option values to labels.

It's not at all clear what you are asking for here. I can't see what your code example is supposed to do.

If you have a test case or can expand on what you are actually trying to achieve then feel free to reopen.

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