Flask-WTF - validate_on_submit() 永远不会执行 [英] Flask-WTF - validate_on_submit() is never executed

查看:37
本文介绍了Flask-WTF - validate_on_submit() 永远不会执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 -

我在 GitHub 上创建了一个示例.

这篇关于Flask-WTF - validate_on_submit() 永远不会执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆