Reputation: 3966
I have a ModelForm
which is rendering a select
field because it points to a ForeignKey
. When the form is rendered, it's displaying the options based the ForeignKey
's __unicode__
definition.
For example, I have a select
field in a form to pick a contact from a Contact
model. The Contact
model has:
def __unicode__(self):
return self.first_name
Thus, my list of contacts in my select
field only show first names.
I know I could just change the __unicode__
definition, but I want to know how to change what is presented int the select
options based on where that select
field is presented. In other words, in some forms, I need to show something like:
{{ contact.first_name}} -- {{ contact.phone_number }}
and in other areas I want to show just:
{{ contact.first_name }}
How do I go about adjusting the ModelForm
so that that specific field, the select
field which is pointing to the ForeignKey
model Contact
displays the full name of the contact?
Upvotes: 2
Views: 1226
Reputation: 2671
As I understand this is a ModelChoiceField
so you can override the label_from_instance
. Docs for reference.
class YourNewChoiceField(ModelChoiceField):
def label_from_instance(self, obj):
return "%s -- %s" % (obj.name, obj.phone_number)
Inside the form use your new field.
class YourForm(ModelForm)
# As you'd normally define your ModelChoiceField field
contact = YourNewChoiceField(queryset=...)
class Meta:
fields = ['contact', ...]
Upvotes: 4