Flask-WTF表单在GET请求期间有错误 [英] Flask-WTF form has errors during GET request
问题描述
@ app.route('/',methods = ['GET' ,'POST'])
def index():
form = ApplicationForm(request.form)
$ b $ if form.is_smit():
print提交
如果form.validate():
打印有效
打印(form.errors)
如果是form。 validate_on_submit():
返回重定向('index')
返回render_template('index.html',form = form)
127.0.0.1 - - [30 / Nov / 2016 16:54:12]GET / HTTP / 1.1200 -
{'department':[u'不是一个有效的选择'],'email':[u'This field is required。'],'csrf_token':['CSRF token missing '],'name':[u'This field is required。'],'address':[u'This field is required。']}
这是一个ge t请求,所以 request.form
是空的。您无条件地调用 validate
,所以您正在验证空数据。所以一切都是无效的这就是为什么 validate_on_submit
存在:它不验证获取请求,因为它们没有表单数据。
删除 if form.validate()
block。
$ b
form.errors
仅在验证后填充,因此将其移动到 validate_on_submit
块之下,否则它将始终显示为空。
另外,你不需要传递 request.form
,Flask-WTF会自动传递它表单被提交。
I have a Flask view with a Flask-WTF form. When I load the page in the browser, the form always has errors, even though I haven't submitted it yet. Why does the form have errors before it is submitted?
@app.route('/', methods=['GET', 'POST'])
def index():
form = ApplicationForm(request.form)
if form.is_submitted():
print "Form successfully submitted"
if form.validate():
print "valid"
print(form.errors)
if form.validate_on_submit():
return redirect('index')
return render_template('index.html', form=form)
127.0.0.1 - - [30/Nov/2016 16:54:12] "GET / HTTP/1.1" 200 -
{'department': [u'Not a valid choice'], 'email': [u'This field is required.'], 'csrf_token': ['CSRF token missing'], 'name': [u'This field is required.'], 'address': [u'This field is required.']}
This is a get request, so request.form
is empty. You're calling validate
unconditionally, so you're validating against empty data. Therefore, everything's invalid. This is why validate_on_submit
exists: it doesn't validate for get requests, since they don't have form data.
Remove the if form.validate()
block.
form.errors
is only populated after validation, so move it below the validate_on_submit
block or it will always appear empty.
Also, you don't need to pass request.form
, Flask-WTF will automatically pass it if the form is submitted.
这篇关于Flask-WTF表单在GET请求期间有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!