Django模板无法正确显示

时间:2011-07-07 22:19:47

标签: python 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

感谢

编辑:

我尝试过Ignacio的解决方案但仍然没有。

3 个答案:

答案 0 :(得分: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 :(得分: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 %}

答案 2 :(得分:0)

快速&amp;肮脏的回答:

# 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和底层数据库 - 使用注释和聚合函数会更好。