我是 django 的新手。
我有这个民意调查应用程序,我想限制选民每次投票每次投票一次。例子:
民意调查#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'
点击投票按钮后会提示此错误
谁能帮我解决这个问题?
谢谢,贾斯汀