我正在尝试制作一个投票应用程序,但我有点卡在“查看投票”页面上。
我想用 Twitter Bootstrap 进度条显示投票,我在 Choice 模型中编写了一个方法来计算与投票中所有其他选项相比的百分比。
但是,当我尝试这样做时{{ choice.percentage }}
,它只会返回......空白。没有。
截屏:
这是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 %}