【发布时间】:2017-08-22 00:51:29
【问题描述】:
我在这里和其他几个地方查看了其他类似的问题,但解决方案似乎对我的问题没有帮助。尽管如此,我没有看到我拥有的这个简单代码与其他类似代码之间有太大区别。尤其是这个Flask - wtforms: Validation always false
forms.validate_on_submit() 总是错误的,我不明白为什么。 我正在阅读 Miguel Grinberg 撰写的 Flask Web Development Book,但我想更改一些内容以了解更多信息。 在 html 模板中使用 wtf.quick_form(form) 时它可以工作,但是如果我删除 quickform 条目并放入表单字段,那么它就不起作用 屏幕只是刷新,它不会将陌生人更改为输入的任何名称
HTML 索引模板
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
<form action="" method='POST'>
{{ form.name.label }} <br>
{{ form.name }}
{{ form.submit }}
</form>
{% endblock %}
相关代码hello.py
from flask import Flask, render_template, request
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, RadioField, TextField, validators
from wtforms.validators import Required
from wtforms.validators import DataRequired
app = Flask(__name__)
class NameForm(Form):
name = StringField('What is your name?',validators=[Required()] )
submit = SubmitField('Submit')
@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm(request.form) #From the docs I read I don't need
# request.form but it
# doesn't work either with it or without it
if form.validate() == True:
name='True' #never happens is not validating or is always set to False for
# some reason
if form.validate_on_submit(): #isn't validating or working
name = form.name.data #'Stranger' will disappear from the html template and
#replaced with the name the user entered in the
# Stringfield
form.name.data = '' #clear stringfield for next round
return render_template('index.html',form=form, name=name)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)'
我不明白\缺少什么? 谢谢
g
【问题讨论】: