永远不会执行validate

永远不会执行validate

我正在使用Flask-WTF:

这是我的表格:

from flask.ext.wtf import Form, TextField

class BookNewForm(Form):
    name = TextField('Name')

这是 Controller :
@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)

现在的问题是,如果您查看我的打印语句,它将始终打印已提交的内容,但从不打印有效的内容,并且永远不会执行validate_on_submit()。为什么?

最佳答案

您没有在HTML表单中插入CSRF字段。

<form method=post>
    {{ form.csrf_token }}
    {{ form.name }}
    <input type=submit>
</form>

form.csrf_token添加到模板(docs)后,该表单将按预期进行验证。

验证表单后,添加print(form.errors)以查看出现的错误。验证之前errors将为空。在这种情况下,会出现有关丢失的错误
@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 -

I created an example on GitHub.

关于python - Flask-WTF-永远不会执行validate_on_submit(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10722968/

10-11 02:26