我经常发现自己在视图中使用 ModelForm 来显示和转换视图。我在模板中显示表单没有任何问题。我的问题是,当我使用这些表单时,表单通常不会使用 is_valid 方法进行验证。问题是我不知道是什么导致了验证错误。
这是视图中的基本示例:
def submitrawtext(request):
if request.method == "POST":
form = SubmittedTextFileForm()
if form.is_valid():
form.save()
return render(request, 'upload_comlete.html')
return render(request, 'failed.html')
else:
form = SubmiittedTextFileForm()
return render(request, 'inputtest.html', {'form': form})
我知道表单未验证,因为我被重定向到 failed.html 模板,但我永远不知道为什么 .is_valid 为 false。如何设置以显示表单验证错误?
有几件事:
你没有采取POST
被发送到 POST。
要查看错误消息,您需要渲染回同一模板。
尝试这个:
def submitrawtext(request):
if request.method == "POST":
form = SubmittedTextFileForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'upload_comlete.html')
else:
print form.errors #To see the form errors in the console.
else:
form = SubmittedTextFileForm()
# If form is not valid, this would re-render inputtest.html with the errors in the form.
return render(request, 'inputtest.html', {'form': form})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)