access object by foreign key in an html template

Date: April 19th 2016
Last updated: April 23rd 2016

Short reminder how to access a field via a foreign key. Use dot notation.

html template

<div id="profilepage">
  <p> {{modelObject.hometown}} </p>
  <p> {{modelObject.FK_toCityTable.cityname }}, 
      {{modelObject.FK_toCountryTable.common_name }} 

EDIT: I have returned to this entry because I had a more complex problem requiring a different solution. In the following example I have extended the builtin Group model with a table called GroupModerator. The goal is to access the field called 'group_status' in the GroupModerator table, via the Group model in an html template.
The Group model is connected to a GroupModerator table by a foreign key.

class GroupModerator(models.Model):
    group_user = models.ForeignKey(User)
    group_id = models.ForeignKey(Group)
    STATUS = (('Open', 'Open'),('Full', 'Full'),)
    group_status = models.CharField(max_length=4, choices=STATUS,default='Open')
The view gets all groups in the database and sends it to groups.html.

def groups(request):
    groups_list = Group.objects.all()
    context = {'groups_list': groups_list }
    return render(request, 'surferprofile/groups.html', context)

The problem is that GroupModerator is the one with the foreignkey defined. So how do I get to this table via the Group model? Reminder: I want "group_status" displayed in the table. In this example I am getting the display label, hence the "get_group_status_display" code.

{% for group in groups_list %}
<td> {{}} </td>
<!-- return a count of all users in this group -->
<td> {{ group.user_set.all.count }}</td>

<!-- give me the status of the group -->
    {{ group.groupmoderator_set.all.0.get_group_status_display }}
{% endfor %}

results matching ""

    No results matching ""