[Fixed]-How to pass data to a template in Django?

25đź‘Ť

âś…

def avail_times(request, club_id):
  courts = Available.objects.filter(club__id=club_id)      
  if courts.count() > 0:
    club_name = courts[0].club.establishment
  else:
    # no results found for this club id!

# perhaps it is better to check explicity if the club exists before going further, 
# eg. Club.objects.get(pk=club_id)
# is club_id passed in as a string? I haven't used django in awhile somethign 
# worth looking into?

return render_to_response('reserve/templates/avail_times.html', {'courts': courts, 'club_name': club_name})


<h1>All available courts for {{ club_name }}</h1>
<ul>
  {% for court in courts %}
    <li>{{ court.club.establishment }}</li>
  {% endfor %}
</ul>

You span foreign key relationships using dot notation. You have to go “through” the foreign key to get to the Club model. This is done through accessing the club attribute. So additionally supposed you wanted to access both the establishment name AND the address, you could add <li>{{ court.club.address }}</li> to display the address too.

Be careful though, you can use django debug toolbar to see how many queries are being executed. if you have a lot of courts you might notice a performance hit. Just something to keep in mind.

Courts is a queryset object. You are trying to access property of court.club which doesn’t exist, as you’ve probably noticed django fails silently when this happens. There are a couple ways of getting club name.

You might want to give some thoughts to your schema. Can clubs have multiple courts?? If not it is “better” to use .get as Zahir suggested. If it can have multiple courts then you should look into a ManyToMany relationship to better reflect this.

👤dm03514

1đź‘Ť

Use render() because render_to_response() is removed since Django 3.0:

views.py:

def avail_times(request, club_id):
    courts = Available.objects.filter(club__id=club_id)      
    if courts.count() > 0:
        club_name = courts[0].club.establishment
    else:
        # no results found for this club id!

    return render(
        request, 
        'reserve/templates/avail_times.html',
        {'courts': courts, 'club_name': club_name}
    )

Django Template:

<h1>All available courts for {{ club_name }}</h1>
<ul>
  {% for court in courts %}
    <li>{{ court.club.establishment }}</li>
  {% endfor %}
</ul>

Leave a comment