根據Django教程,您應該使用cleaned_data字典訪問表單字段。我想知道爲什麼我無法直接訪問表單的屬性?我的表單驗證很好,但是當我嘗試訪問它時,Django抱怨對象沒有該屬性。我在下面添加了一些代碼,希望能幫助診斷問題。在django視圖中訪問表單字段作爲屬性
形式:
class CustomForm(forms.Form):
description = forms.CharField(widget = forms.TextInput(attrs = {'placeholder' : 'enter some text'}), label = "My form")
查看:
def process_form(request):
if request.method != 'POST':
raise Http404
myForm = CustomForm(request.POST)
if not myForm.is_valid():
c = RequestContext(request)
return render_to_response('home/index.html', {'form' : myForm }, c)
# debug
print 'Description: ' + myForm.description # this does NOT work
# print 'Description: ' + myForm.cleaned_data['description'] # this does work
我得到以下錯誤: 'CustomForm' 對象有沒有屬性 '的描述'。我在文檔中錯過了一些說我無法做到的事情嗎?
我知道我可以使用cleaned_data訪問它。我不明白的是爲什麼我無法使用屬性本身訪問它:myForm.description。在引擎蓋下究竟發生了什麼,阻止我訪問它? – 2012-03-13 16:20:18