Python Django Session

时间:2012-04-25 07:52:28

标签: django

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

点击投票按钮后会出现此错误

是谁能帮我解决这个问题?

谢谢, 贾斯汀

1 个答案:

答案 0 :(得分:3)

如果您还没有投票,request.session['has_voted']尚未设置,那么您会收到KeyError,因为缺少'has_voted'密钥。

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

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