0
我是新的django。Python Django Session
我有這個民意調查程序,我想限制選民每次投票每次會議投票。例如:
調查#1
調查#2
的時候我會投來輪詢#1,之後我也不會選投票#1,但我可以投票調查#2。
所以我決定把投票ID放入一個列表中,然後檢查它是否存在。
poll_list = [] #declare the poll_list variable
@login_required
@never_cache
def vote(request, poll_id):
global poll_list #declare it as global
p = get_object_or_404(Poll, pk=poll_id)
try:
selected_choice = p.choice_set.get(pk=request.POST['choice'])
except (KeyError, Choice.DoesNotExist):
return render_to_response('polls/detail.html', {
'poll': p,
'error_message': "You didn't select a choice.",
}, context_instance=RequestContext(request))
else:
if poll_id in request.session['has_voted']: #here is the checking happens
return HttpResponse("You've already voted.")
selected_choice.votes += 1
selected_choice.save()
poll_list.append(poll_id) #i append the poll_id
request.session['has_voted'] = poll_list #pass to a session
return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
return HttpResponse("You're voting on poll %s." % poll_id)
我得到了一個錯誤:
KeyError at /polls/3/vote/
'has_voted'
我點擊投票按鈕
人誰可以幫我這個後這個錯誤提示?
感謝, 賈斯汀
與這個問題無關:請注意,全局'poll_list'不會很好:如果在生產中運行多個django進程,每個進程都有自己的那個列表版本。最好將民意調查堅持到數據庫中。 – 2012-04-25 07:59:59
我該怎麼做?請幫忙。 – justin 2012-04-25 08:11:37
其實,現在我讀了一下你的代碼好一點:你不需要全局poll_list。在你的方法開始時,做一個'poll_list = request.session.get('has_voted',[])''。會話是您想要存儲它的地方。當它實際上是每個會話時,無需在全球範圍內跟蹤它。 – 2012-04-25 08:18:38