Django. Access the foreign key fields in the template from a form object
<p>I use Django 1.8.14. I have two models:</p>

<pre><code>class Event(models.Model):
    title = models.CharField(max_length=255,)
    date = models.DateTimeField()
    ...
    def __unicode__(self):
       return self.title

class Card(models.Model):       
   user = models.ForeignKey(MyUser, related_name="user")
   event = models.ForeignKey(Event,) 
   ...
</code></pre>

<p>Card model form:</p>

<pre><code>class CardForm(forms.ModelForm):
   def __init__(self, *args, **kwargs):
      super(CardForm, self).__init__(*args, **kwargs)
      self.fields['event'].empty_label = None

class Meta:
    model = Card
    fields = ('event', )
    widgets = {'event': forms.RadioSelect, }
</code></pre>

<p>I render form like this:</p>

<pre><code>&lt;form method="POST"&gt;
    {% csrf_token %}
    {% for choice in cardform.event %}
       {{ choice.tag }}
       {{ choice.choice_label }}
    {% endfor %}
&lt;/form &gt;
</code></pre>

<p>In the label of each radio button I need to display both fields value "title" and "date" of Event model which is ForeignKey of Card. Now label  includes only "title" value. What is the best way to do it?
I tried <strong>{{ cardform.instance.event.date }}</strong> but it doesn't work.</p>

<p>I've found a solution.</p>

<pre><code>class CardForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
       super(CardForm, self).__init__(*args, **kwargs)           
       self.fields['event'].label_from_instance = lambda obj: "%s %s" % (obj.title, obj.date)
</code></pre>

python django django-forms