3

I've got a form template, to which I'm passing the form info as well as the object itself. I can use {{ object.get_FOO_display }} no problem for choice fields when the choice field is a part of the object itself, but I'm looking for an easy way to do the same for the foreign fields that are in the form.

I'm building this into a class-based view, so ideally any suggestions could be coded independent of references to specific fields.

Thanks!

ollyb
  • 33
  • 4
  • When you include `{{ object.FOO }}` in a template (where 'FOO' is the foreign field), it gives you the __unicode__() return value for FOO. Isn't that adequate? – jcfollower Aug 15 '11 at 18:02
  • **Take a look at this solution:** http://stackoverflow.com/a/7571539/497056 – Ivan Kharlamov Feb 19 '12 at 14:06

1 Answers1

1

If I'm not mistaken and you are trying to get display value for a django model instance with a choices attribute, you could simply:

object.foreign_key_field.get_FOO_display

However, if you are working backwards (ie trying to get display value for a model instance that has a foreign key pointing to your object instances model and a related_name attribute of fk_related_name) then:

object.fk_related_name.get_query_set()[i].get_FOO_display

get_query_set returns a queryset, so you could either iterate over the queryset with a {% forloop %} or provide the index [i] of the object you want, as above.

If these don't work and you're still uncertain, post you object instance model and foreign_key model.

Eric H.
  • 6,894
  • 8
  • 43
  • 62