0

I have a django ForeignKey like this

class Example(models.Model):
    Field = models.CharField("Description", max_length=50)
    AnotherField = models.CharField("Extra Info", max_length=50)
    def __unicode__(self):
        return self.Field

By default the HTML select will contain as description the values of the Example.Field field. I can't change the unicode method. The real problem is when I need another values a model. I need something like This:

class SecondExapmle(models.Model):
    Description = models.CharField("Description", max_length=50)
    Foreign     = models.ForeignKey(Example)
    SecondData  = models.ForeignKey(Example, show_value_from_column="AnotherField") # this line

Suposing that SecondExample has the next records:

-----------------------------
| id | field | anotherfield |
-----------------------------
| 1  | Str   | Another Str  |
| 2  | Str2  | Another2     |
-----------------------------

I need that the Form's Foreign select contains the next HTML:

<select id="id_foreign">
   <option value='1'>Str</option>
   <option value='2'>Str2</option>
</select>

And the Forms AnotherField select contains the next HTML:

<select id="id_anotherfield">
   <option value='1'>Anotheer Str</option>
   <option value='2'>Another2</option>
</select>
MikeVelazco
  • 885
  • 2
  • 13
  • 30
  • Have you tried the `help_text` keyword argument for `ForiegnKey`? So, `ForeignKey(Example, help_text="AnotherField")`. – Johndt Aug 14 '14 at 17:38
  • Without a related_name this model will be invalid as the Example model is related twice from SecondExample, see [link](http://stackoverflow.com/questions/543377/how-can-i-have-two-foreign-keys-to-the-same-model-in-django) – crhodes Aug 14 '14 at 17:41
  • Is true that I need to set the related name, but I need to set a different descripion in the selects. The `help_text` only will add an static value to the `title` property of the `HTML select` – MikeVelazco Aug 14 '14 at 18:04

2 Answers2

0

The documentation for forms.ModelChoiceField - which is the field that is used for a ForeignKey on a form - shows exactly what to do here. You need to subclass the form field and define a label_from_instance method.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

Use verbose_name='':

models.ForeignKey(Example, verbose_name='Example')
double-beep
  • 5,031
  • 17
  • 33
  • 41
TitanRain
  • 99
  • 1
  • 4