如何在Django中使用模板调用模型上的自定义方法?

时间:2013-09-21 14:44:15

标签: python django templates twitter-bootstrap methods

我正在尝试制作民意调查应用,而且我有点卡在“查看民意调查”页面上。

我想用Twitter Bootstrap进度条显示投票,我在Choice模型中编写了一个方法来计算与投票中所有其他选项相比的百分比。

但是,当我尝试{{ choice.percentage }}时,它只会返回...空白。什么都没有。

屏幕截图:screenshot

这是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

这里是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 %}

1 个答案:

答案 0 :(得分:2)

你的问题在于这个方法:

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():返回Choice个对象的查询集。

现在,在视图中,如果您尝试choice.percentage(),您会发现错误。

要解决此问题,请尝试

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