Django 模板未正确显示
几个月前离开 Django 后,我又回到了它,并回到了我根据教程制作的民意调查应用程序。我添加了总票数和百分比。百分比,例如,显示特定民意调查选项占总票数的百分比。没有错误,什么也没有。它只是根本不显示。我的意思是,除了百分比之外,一切都显示出来。就像我从来没有在模板中写过它一样!
results.html:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice }} - {{ choice.percentage }} ({{ choice.votes }}) </li>
{% endfor %}
</ul><br /><br />
<p>Total votes for this poll: {{ total }} </p>
views.py:
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
choices = list(p.choice_set.all())
total_votes = sum(c.votes for c in choices)
percentage = {}
for choice in choices:
vote = choice.votes
vote_percentage = int(vote*100.0/total_votes)
choice.percentage = vote_percentage
return render_to_response('polls/results.html', {'poll': p, 'total': total_votes}, context_instance=RequestContext(request))
帮助? :P
谢谢
编辑:
我尝试了伊格纳西奥的解决方案,但仍然不行。
I got back to Django after leaving it a few months ago, and came back to that polls app I made from the tutorial. I added total votes and percentage. Percentage, as in, displaying what percentage of total votes the specific poll choice has. No error, no nothing. It just doesn't show at all. I mean, everything shows except the percentage. Like I never wrote it in the template!
results.html:
<h1>{{ poll.question }}</h1>
<ul>
{% for choice in poll.choice_set.all %}
<li>{{ choice.choice }} - {{ choice.percentage }} ({{ choice.votes }}) </li>
{% endfor %}
</ul><br /><br />
<p>Total votes for this poll: {{ total }} </p>
views.py:
def results(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
choices = list(p.choice_set.all())
total_votes = sum(c.votes for c in choices)
percentage = {}
for choice in choices:
vote = choice.votes
vote_percentage = int(vote*100.0/total_votes)
choice.percentage = vote_percentage
return render_to_response('polls/results.html', {'poll': p, 'total': total_votes}, context_instance=RequestContext(request))
Help? :P
thanks
EDIT:
I tried Ignacio's solution and still no go.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能像模板中那样对变量建立索引。我建议以另一种方式进行:
...
You can't index dictionaries on a variable like that in templates. I recommend doing it the other way:
...
您正在查询选项两次。进入视图
choices = list(p.choice_set.all())
后,再次进入模板{% for choice in poll.choice_set.all %}
。这意味着您的计算将永远不会被使用。如果你想计算视图中的百分比并在模板中访问它,那么你需要在 context: 中传递它,然后在模板中访问它:
You are querying the choices twice. Once in the view
choices = list(p.choice_set.all())
and again in the template{% for choice in poll.choice_set.all %}
. This means that your calculation will never be used. If you want to calculate the percentage in the view and access it in the template then you need to pass it in the context:and then access it in the template:
快速&肮脏的答案:
在模板中:
但这并没有很好地利用orm和底层数据库——使用注释和聚合函数会更好。
Quick & dirty answer:
and in the template:
but that's not making good use of the orm and underlying db - using annotations and aggregation functions would be way better.