Django 模板未正确显示

1 投票
3 回答
816 浏览
提问于 2025-04-16 21:03

我几个月前离开了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

谢谢

编辑:

我试过Ignacio的解决方案,但还是不行。

3 个回答

0

简单粗暴的回答:

# views.py
def results(request, poll_id):
    p = get_object_or_404(Poll, pk=poll_id)
    # XXX code smell: one shouldn't have to turn a queryset into a list
    choices = list(p.choice_set.all())

    # XXX code smell: this would be better using aggregation functions
    total_votes = sum(c.votes for c in choices)

    # XXX code smell: and this too   
    for choice in choices:
       vote = choice.votes
       vote_percentage = int(vote*100.0/total_votes)
       choice.percentage = vote_percentage

  context = {
      'poll': p, 
      'total': total_votes, 
      'choices'  :choices
      }
  return render_to_response(
      'polls/results.html',
      context,
      context_instance=RequestContext(request)
      )

在模板里:

 {% for choice in choices %}
    <li>{{ choice.choice }} - {{ choice.percentage }} ({{ choice.votes }}) </li>
 {% endfor %}

不过这样做并没有充分利用ORM和底层数据库,使用注解和聚合函数会更好。

2

在模板中,你不能像那样用变量来索引字典。我建议你换个方法来做:

for choice in choices:
   ...
  choice.percentage = vote_percentage

...

{% for choice in poll.choice_set.all %}
    <li>{{ choice.choice }} - {{ choice.percentage }} ({{ choice.votes }}) </li>
{% endfor %}
1

你在查询选项的时候做了两次。第一次是在视图里用 choices = list(p.choice_set.all()),第二次是在模板里用 {% for choice in poll.choice_set.all %}。这样的话,你的计算结果就不会被用到。如果你想在视图里计算百分比,然后在模板中使用这个结果,你需要把它放到上下文中:

def results(request, poll_id):
    ...
    return render_to_response('polls/results.html', {'poll': p, 'total': total_votes, 'choices': choices}, context_instance=RequestContext(request))

然后在模板中访问它:

{% for choice in choices %}
    <li>{{ choice.choice }} - {{ choice.percentage }} ({{ choice.votes }}) </li>
{% endfor %}

撰写回答