How to transfer data to a template in Django?

In the template below, I am trying to get the name of the court (which is fixed in the "creation" field). I pass "club_id" through the avail_times function, but how do I pass the "establishment" field passed through the template from this?

Model:

class Club(models.Model): establishment = models.CharField(max_length=200) address = models.CharField(max_length=200) def __unicode__(self): return self.establishment class Available(models.Model): club = models.ForeignKey(Club) court = models.CharField(max_length=200) avail_time = models.DateTimeField('available time') def __unicode__(self): return self.court 

Function:

 def avail_times(request, club_id): courts = Available.objects.filter(club__id=club_id) return render_to_response('reserve/templates/avail_times.html', {'courts': courts}) 

Template:

  <h1>All available courts for {{ court.club }}</h1> <ul> {% for court in courts %} <li>{{ court }}</li> {% endfor %} </ul> 
+6
source share
1 answer
 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 must go through the foreign key to go to the Club model. This is achieved by accessing the Club attribute. In addition, presumably you wanted to access both the name of the institution and the address, you can add <li>{{ court.club.address }}</li> to display the address.

However, be careful, you can use the django debug toolbar to find out how many requests are being executed. if you have many ships, you may notice a performance hit. Just need to keep in mind.

Courts are a request object. You are trying to access the court.club property, which is not there, as you probably noticed that django fails when this happens. There are several ways to get the name of the club.

You might want to share your thoughts with your circuit. Can clubs have multiple ships? If not β€œbetter,” use .get , as Zahir suggested. If he can have several ships, then you should study ManyToMany's relationship to better reflect this.

+15
source

Source: https://habr.com/ru/post/915791/


All Articles