2011-07-07 77 views
0

幾個月前我離開Django後回到了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

感謝

編輯:

我試圖伊格納西奧的解決方案,仍然沒有去。

回答

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 %} 
+0

謝謝,那就是訣竅!爲什麼這樣做了兩次查詢?不是以任何方式保存在choice.percentage中的值? – Lockhead

+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 %} 
+0

您的意思是將百分比添加到模型Choice?我可能會嘗試,但爲了將來的參考,我如何修復當前的代碼? – Lockhead

+0

您*無法*修復當前的代碼。並且沒有必要爲模型添加「百分比」。 –

+0

這有點令人困惑...... Django如何知道choice.percentage是什麼?我認爲它可以與模板一起工作,因爲我讀過可以以這種方式訪問​​字典的地方,但它如何在views.py中以這種方式工作? – Lockhead

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和底層數據庫 - 使用註釋和聚合函數會更好。