2014-03-19 26 views
0

這一個真的讓我很難過。任何幫助,將不勝感激。Django錯誤:在視圖中的UnboundLocalError

UnboundLocalError at /addauthor 
local variable 'form' referenced before assignment 
Request Method: POST 
Request URL: http://127.0.0.1:8000/addauthor 
Django Version: 1.4 
Exception Type: UnboundLocalError 
Exception Value:  
local variable 'form' referenced before assignment 
Exception Location: C:\Users\Nir\desktop\club\blog\views.py in addauthorView, line 8 
Python Executable: C:\Python27\python.exe 
Python Version: 2.7.6 

這裏是我的views.py:

from django.shortcuts import render 
from blog.forms import ContactForm 
from django.http import HttpResponseRedirect 

def addauthorView(request): 
    if request.method == 'POST': 
    f = ContactForm(request.POST) 
    if form.is_valid(): 
      first_name = form.cleaned_data['firstname'] 
      last_name = form.cleaned_data['lastname'] 
      user_email = form.cleaned_data['email'] 
      c = Contact(firstname=first_name, lastname=last_name, email=user_email) 
      c.save() 
      return HttpResponseRedirect('thanks/') 
    else: 
      form = ContactForm(request.POST) 
      return render(request, 'addauthor.html', {'form': ContactForm}) 
else: 
    return render(request, 'addauthor.html', {'form': ContactForm}) 


def thanksView(request): 
    return render(request, 'thanks.html') 

我可以根據要求張貼在我的Django項目其他的事情,但似乎這個問題是從意見快到了,我不知道爲什麼。

回答

3

您正在使用form變量而未定義它。替換:

f = ContactForm(request.POST) 

有:

form = ContactForm(request.POST) 
+1

而且,僅供參考,學習如何在SO [接受的答案](http://meta.stackexchange.com/a/5235/219368)(您目前沒有任何可接受的答案)。 – alecxe

+0

謝謝!並做了! – ApathyBear