[Answer]-What is the best way to display data in a template in Django?

1đź‘Ť

âś…

Well, you don’t seem to have a Court model, so I’m not sure why you’re trying to call court_set.all. You could use club.available_set.all to show the list of Available instances for that club, which might be what you mean.

0đź‘Ť

First step would be to set up your models appropriately. Clubs have Courts and Courts have Available Times. Clubs don’t have Available Times, which is how you have it set up now. Further, “taken” is a status of an available time; it shouldn’t be a model itself. Try something like:

class Club(models.Model):
    establishment = models.CharField(max_length=200)
    address = models.CharField(max_length=200)

    def __unicode__(self):
        return self.establishment

class Court(models.Model):
    club = models.ForeignKey(Club, related_name='courts')
    name = models.CharField(max_length=200)

class CourtTime(models.Model):
    AVAILABLE = 0
    TAKEN = 1
    STATUS_CHOICES = (
        (AVAILABLE, 'Available'),
        (TAKEN, 'Taken'),
    )

    court = models.ForeignKey(Club, related_name='times')
    time = models.DateTimeField('available time')
    status = models.PositiveSmallIntegerField(choices=STATUS_CHOICES, default=STATUS_CHOICES[AVAILABLE])

    def __unicode__(self):
        return self.court

Then, I would suggest a custom manager on CourtTime to return available/taken querysets:

class CourtTimeQuerySet(models.query.QuerySet):
    def available(self):
        return self.filter(status=CourtTime.STATUS_CHOICES[CourtTime.AVAILABLE])

    def taken(self):
        return self.filter(status=CourtTime.STATUS_CHOICES[CourtTime.TAKEN])

class CourtTimeManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self, *args, **kwargs):
        return CourtTimeQuerySet(self.model)

    def available(self, *args, **kwargs):
        return self.get_query_set().available(*args, **kwargs)

    def taken(self, *args, **kwargs):
        return self.get_query_set().taken(*args, **kwargs)

Then, add it to your model:

class CourtTime(models.Model):
    ...
    objects = CourtTimeManager()

With all that in place, you can just do the following in your template:

{% for court in club.courts.all %}
    <h2>{{ court.name }}</h2>
    <ul>
        {% for time in court.times.available %}
        <li>{{ time|date:"m/d/Y g:i A" }}</li>
        {% endfor %}
    </ul>
{% endfor %}
👤Chris Pratt

Leave a comment