幾個月前我離開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
感謝
編輯:
我試圖伊格納西奧的解決方案,仍然沒有去。
謝謝,那就是訣竅!爲什麼這樣做了兩次查詢?不是以任何方式保存在choice.percentage中的值? – Lockhead
從我可以告訴百分比不是一個模型字段,我沒有看到在選擇模型實例調用'保存',即使它是視圖的任何東西。 –