user1438098
user1438098

Reputation: 2399

How do I call a custom method on a model with a template in Django?

I'm trying to make a poll app, and I'm kinda stuck on the "view poll" page.

I want to display the votes with a Twitter Bootstrap progress bar, and I wrote a method in the Choice model to calculate the percentage compared to all the other choices on the poll.

However, when I try doing {{ choice.percentage }} it just returns... blank. nothing.

Screenshot: screenshot

Here's models.py:

from django.db import models

class Poll(models.Model):
    question = models.CharField(max_length=256)
    pub_date = models.DateTimeField('date published')

    def __unicode__(self):
        return self.question

class Choice(models.Model):
    poll = models.ForeignKey(Poll)
    choice_text = models.CharField(max_length=256)
    votes = models.IntegerField(default=0)

    def __unicode__(self):
        return self.choice_text

    def percentage(self):
        total = 0.0
        for ch in self.poll.choice_set.all():
            total = total + ch
        return (self.votes/total)*100

And here's view_poll.html:

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

{% block title %}Viewing poll #{{ poll.id }} {% endblock %}

{% block content %}
<div class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title text-center">{{ poll.question }}</h3>
    </div>
    <div class="panel-body">
        {% for choice in poll.choice_set.all %}
        <div class="row">
            <div class="col-md-3 text-right">{{ choice.choice_text }}</div>
            <div class="col-md-9">
                <div class="progress">
                    <div class="progress-bar" role="progressbar" aria-valuenow="{{ choice.percentage }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ choice.percentage_of_votes }}%">
                        <span class="sr-only">{{ choice.votes }} out of {{ total_votes }}</span>
                    </div>
                </div>
            </div>
        </div>
        {% endfor %}
    </div>
{% endblock %}

Upvotes: 1

Views: 139

Answers (1)

karthikr
karthikr

Reputation: 99660

Your problem is in this method:

def percentage(self):
    total = 0.0
    for ch in self.poll.choice_set.all():
        total = total + ch
    return (self.votes/total)*100

self.poll.choice_set.all(): returns a queryset of Choice objects.

Now, in the view if you try to do choice.percentage(), you will notice the error.

To fix this, try

def percentage(self):
    total = 0.0
    for ch in self.poll.choice_set.all():
        total = total + ch.votes
    return (self.votes/total)*100

Upvotes: 3

Related Questions