FoamyGuy
FoamyGuy

Reputation: 46856

Django View / Template how to know the max value from a model

I am working on the https://docs.djangoproject.com tutorial project which contains two models.

Poll:

class Poll(models.Model):
    question = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')
    def was_published_recently(self):
        now = timezone.now()
        return now - datetime.timedelta(days=1) <= self.pub_date < now
    was_published_recently.admin_order_field = 'pub_date'
    was_published_recently.boolean = True
    was_published_recently.short_description = 'Published recently?'
    def __unicode__(self):
        return self.question

and Choice:

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=200)
    votes = models.IntegerField(default=0)
    def __unicode__(self):
        return self.choice_text

There is a Detail View that shows a Poll question, along with the choices for that question and allows the user to vote. And a Result View which shows the question again, along with the current number of votes for each choice.

I've got everything displaying properly, but I am trying to add a feature that is not covered in the tutorial, and I am unsure of how to go about doing it. I'd like to make it so that on the results page the choice with the most votes gets some kind of special formatting to denote it as the current leader.

Right now In the template I have just a for loop that outputs each choice and it's value in whatever order they are stored.

{% extends "polls/base.html" %}

{% block content %}
<h1>{{ poll.question }}</h1>

<ul>
{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li>
{% endfor %}
</ul>

<a href="{% url 'polls:detail' poll.id %}">Vote again?</a>
{% endblock %}

I am a bit stuck on trying to figure out how to know if I am on the choice with the most votes when I am inside that for loop, so that I can have some sort of conditional to change the formatting.

I just need a bit of a nudge in the right direction. Is there some way within the template itself that I can know which choice has the most votes? Or do I need to figure that out in the View and pass it along to the template? And if both are possible would one or the other be considered preferred?

Upvotes: 3

Views: 2747

Answers (1)

erthalion
erthalion

Reputation: 3244

If I understand correctly, you can write custom assignment template tag, and then use it in the if...else.

{% get_max_votes poll.choice_set.all as leader %}
{% for choice in poll.choice_set.all %}
    {% ifequal choice leader %}
    {% endif %}
{% endfor %}

Upvotes: 1

Related Questions