Python 如何在Django中使用模板对模型调用自定义方法?
我正在尝试制作一个民意测验应用程序,但我被卡在了“查看民意测验”页面上 我想用Twitter引导进度条显示投票,我在选择模型中编写了一个方法来计算与投票中所有其他选择相比的百分比 但是,当我尝试执行Python 如何在Django中使用模板对模型调用自定义方法?,python,django,templates,twitter-bootstrap,methods,Python,Django,Templates,Twitter Bootstrap,Methods,我正在尝试制作一个民意测验应用程序,但我被卡在了“查看民意测验”页面上 我想用Twitter引导进度条显示投票,我在选择模型中编写了一个方法来计算与投票中所有其他选择相比的百分比 但是,当我尝试执行{{choice.percentage}}时,它只返回。。。空白。没什么 截图: 下面是models.py: from django.db import models class Poll(models.Model): question = models.CharField(max_leng
{{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\u 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 %}
{%extensed“quickpoll\u web/base.html”%}
{%block title%}查看轮询{{{poll.id}{%endblock%}
{%block content%}
{{poll.question}
{poll.choice_set.all%}
{{choice.choice_text}
{{choice.voces}}在{{total_voces}中{{choice.voces}}
{%endfor%}
{%endblock%}
您的问题在于此方法:
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\u 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
哪里定义了
投票百分比
?您将样式设置为width:{{choice.percentage\u of_voces}}%
。如果def percentage(self):返回50,您会得到什么?这将确定percentage是否像您预期的那样被调用,并将指向一个已断开的查询。您的浏览器告诉您该页面的来源是什么?你能在浏览器开发工具中看到
标记吗?@msw如果我用return 50替换它,它仍然是空的。@MartijnPieters这只是重命名它以适应它的剩余内容,因此,如果我修复了它,它仍然是空的。谢谢,修复了它!