Jis*_*son 11 python django-templates django-forms django-views
我正在尝试使用django文档生成表单.我不断得到错误:
'TestForm' object has no attribute 'cleaned_data'
Run Code Online (Sandbox Code Playgroud)
即使form.is_valid是True(它打印我的代码的'形式是有效'行).以下是我的代码的相关部分.
urls.py
url(r'^test/',views.test),
Run Code Online (Sandbox Code Playgroud)
forms.py
from django import forms
class TestForm(forms.Form):
name = forms.CharField()
Run Code Online (Sandbox Code Playgroud)
views.py
def test(request):
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid:
print 'form is valid'
print form.cleaned_data
else:
print 'form not valid'
else:
form = TestForm()
return render_to_response('User/Test.html',{'form': form},context_instance=RequestContext(request))
Run Code Online (Sandbox Code Playgroud)
的test.html
<form action="" method="post">{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)
jul*_*ria 41
您没有触发表单的清理和验证,这是通过调用is_valid()方法(注意括号())来实现的,这就是您没有清理数据的原因.
更正:
if request.method == 'POST':
form = TestForm(request.POST)
if form.is_valid():
print 'form is valid'
print form.cleaned_data
...
Run Code Online (Sandbox Code Playgroud)