2012-04-26 52 views
0

我是新的django。Python Django UnboundLocalError

我有這樣的代碼我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 

請幫助我。我不明白爲什麼我不斷收到此錯誤。 謝謝

回答

1

您正在收到此錯誤,因爲在您的方法中,您只在if條件中創建變量poll_list。因此,如果該條件爲false,則不存在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) 
+0

謝謝,我會稍後再試。需要去... – justin 2012-04-26 06:58:20

+0

'KeyError at/polls/3/vote /'voted_on''我得到了這個錯誤 – justin 2012-04-26 07:01:53

+0

我已經修復它。如果request.session.get('voted_on',False):'to'if request.session.get('voted_on')== None: – justin 2012-04-26 07:06:39

0

分配給名稱會使編譯器認爲它是本地的。在函數的開頭使用global poll_list來改變它。

但是這會導致其他問題,所以您應該重新架構函數。