0

我是 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'

点击投票按钮后会提示此错误

谁能帮我解决这个问题?

谢谢,贾斯汀

4

1 回答 1

3

如果你还没有投票,request.session['has_voted']还没有被设置,那么你会得到一个 KeyError 因为'has_voted'密钥丢失。

您可以使用,缺失request.session.get('has_voted', [])时默认为空列表。has_voted

(请注意,这has_voted听起来像是一个真/假值,voted_on可能会更好)。

于 2012-04-25T07:58:25.777 回答