﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
28316	ModelChoiceField to_field_name doesn't work if it's different from the model field's to_field	László Károlyi	Marc Gibbons	"Hey guys,

I have two models something along the following:
{{{#!python
class M1(Model):
    code = CharField()
    name = CharField()

class M2(Model):
    m1 = ForeignKey(to=M1)
}}}

I have a custom modelform, something along:

{{{#!python

class MyForm(ModelForm):
    m1 = ModelChoiceField(to_field_name='code')
    class Meta(object):
        model = M2
        exclude = ()
}}}

When I try to render this form with an instance of `M2`, because of `to_field_name` not being `pk` of `m1`, the form will render without the option pointing to `M1` selected.

I managed to track the problem back to `BoundField.value()`, which calls `self.field.prepare_value(data)` with the `PK` passed to the instance of the `ModelChoiceField`. There, `ModelChoiceField.prepare_value()` should be able to know how to resolve the passed `PK` to the parameter in `to_field_name`, but it doesn't do it.

Because of that, I'm forced not to pass the `to_field_name` parameter, and let the select widget render itself with `PK`s instead of the wished `code` fields.

Please look into this, should be fairly easy to reproduce. As I could see from googling, [https://stackoverflow.com/questions/9827057/django-modelchoicefield-use-something-other-than-id#comment21720211_11522820 this has formerly already been a problem], and now it's present again."	Bug	assigned	Forms	dev	Normal			Dmytro Litvinov	Accepted	1	0	0	1	0	0
