Flask-WTF - validate_on_submit() 永远不会执行 [英] Flask-WTF - validate_on_submit() is never executed
问题描述
我正在使用 Flask-WTF:
I'm using Flask-WTF:
这是我的表格:
from flask.ext.wtf import Form, TextField
class BookNewForm(Form):
name = TextField('Name')
这是控制器:
@book.route('/book/new', methods=['GET', 'POST'])
def customers_new():
form = BookNewForm()
if form.is_submitted():
print "submitted"
if form.validate():
print "valid"
if form.validate_on_submit():
flash("Successfully created a new book")
return redirect(url_for('.books_show'))
return render_template('views/books_new.html', form=form)
现在的问题是,如果您查看我的打印语句,它总是打印已提交,但它从不打印 valid 并且从不执行 validate_on_submit().为什么?
Now the problem is, if you look at my print statements, it always prints submitted, but it NEVER prints valid and validate_on_submit() is never executed. Why?
推荐答案
您没有在 HTML 表单中插入 CSRF 字段.
You're not inserting the CSRF field in the HTML form.
<form method=post>
{{ form.csrf_token }}
{{ form.name }}
<input type=submit>
</form>
将 form.csrf_token
添加到模板后 (docs),表单将按预期进行验证.
After adding form.csrf_token
to the template (docs), the form will validate as expected.
在验证表单后添加 print(form.errors)
以查看引发的错误.errors
在验证前将为空.在这种情况下,有一个关于missing的错误
Add print(form.errors)
after validating the form to see the errors that were raised. errors
will be empty before validation. In this case, there is an error about missing
@book.route('/book/new_no_csrf', methods=['GET', 'POST'])
def customers_new_no_csrf():
form = BookNewForm()
print(form.errors)
if form.is_submitted():
print "submitted"
if form.validate():
print "valid"
print(form.errors)
if form.validate_on_submit():
flash("Successfully created a new book")
return redirect(url_for('.books_show'))
return render_template('books_new.html', form=form)
{}
submitted
{'csrf_token': [u'CSRF token missing']}
127.0.0.1 - - [29/May/2012 02:01:08] "POST /book/new_no_csrf HTTP/1.1" 200 -
127.0.0.1 - - [29/May/2012 02:01:08] "GET /favicon.ico HTTP/1.1" 404 -
这篇关于Flask-WTF - validate_on_submit() 永远不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!