0

我是 django 的新手。

我的views.py下有这段代码

poll_list = []

@login_required
@never_cache
def vote(request, poll_id):
    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 detail(request, poll_id, error_message="You didn't select a choice.")
    else:
        if request.session.get('voted_on', False):
            poll_list = []
            request.session['voted_on'] = poll_list

        if poll_id in request.session.get('voted_on', []):
            return detail(request, poll_id, has_voted="You have already voted.")

        selected_choice.votes += 1
        selected_choice.save()

        poll_list.append(poll_id)
        request.session['voted_on'] = poll_list
        return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
    return HttpResponse("You're voting on poll %s." % poll_id) 

我收到了这个错误:

UnboundLocalError at /polls/3/vote/
local variable 'poll_list' referenced before assignment

请帮助我..我不明白为什么我不断收到这个错误。谢谢

4

2 回答 2

1

您收到此错误是因为在您的方法中,您只是poll_list在 if 条件中创建变量。因此,如果该条件为假,则没有poll_list,因此当您尝试在 中使用它时poll_list.append(poll_id),Python 会给您该错误。

我认为您要做的是使用您在方法之外声明的全局变量,这不是做您想做的事情的正确方法。

“错误”的解决方法是添加global poll_list您的方法。

正确的解决方法是重组您的方法:

# poll_list = [] - not needed

@login_required
@never_cache
def vote(request, poll_id):
    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 detail(request, poll_id, error_message="You didn't select a choice.")
    else:
        poll_list = request.session.get('voted_on', [])

        if poll_id in poll_list:
            return detail(request, poll_id, has_voted="You have already voted.")

        selected_choice.votes += 1
        selected_choice.save()

        poll_list.append(poll_id)
        request.session['voted_on'] = poll_list
        return HttpResponseRedirect(reverse('poll_results', args=(p.id,)))
    return HttpResponse("You're voting on poll %s." % poll_id) 
于 2012-04-26T06:44:35.477 回答
0

分配给名称会使编译器认为它是本地的。global poll_list在函数的开头使用来改变它。

但这会导致其他问题,因此无论如何您都应该重新架构该功能。

于 2012-04-26T06:40:53.523 回答