python-2.7 - Flask WTForms 表单无法验证

标签 python-2.7 flask sqlalchemy wtforms

我无法验证某个简单的 Flask WTForm。

经过几天的奋斗,我已经尝试了我能想到的一切。总的来说,我对 Flask 和 Web 编程还很陌生。

这是我的代码的精简但有效的版本。测试代码的唯一操作(除了提交表单之外)是将消息打印到终端。运行时的样子:

Screenshot of running code

这是views.py:

    # -*- coding: utf_8 -*-
...

@app.route('/test/new/', methods=['GET','POST'])
def newTest():
    form = TestForm(request.form)
    if form:
        print 'request.form.get(\'name\') is %s' % (request.form.get('name'),)
    if request.method == 'POST':
        print 'in newTest(), request is POST'
        if form.validate():
            print 'form validates'
            return redirect(url_for('allTests'))
        else:
            print 'form does not validate'
            return render_template('newTest.html', form=form)
    else:
        return render_template('newTest.html', form=form)

这是 forms.py:

class TestForm(Form):
    name = StringField(u"Test Name", [validators.InputRequired()])
    address = StringField(u"Test Address", [validators.InputRequired()])

    submit = SubmitField(u"Submit")

模型.py:

from sqlalchemy import Column, Integer, Unicode
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class TestModel(Base):

    __tablename__ = 'test'

    name = Column(Unicode(80), nullable = False)
    id = Column(Integer, primary_key = True)
    address = Column(Unicode(80), nullable = False)

和模板:

<html lang="en">
<head>
    <meta charset="utf-8">
    <title>New Test</title>
</head>
<body>
    <div>
        <form action="{{ url_for('newTest') }}" method="POST" name="add_rest">
        <ul>
            <li>Name: {{ form.name }}</li>
            <li>Address: {{ form.address }}</li>
        </ul>
        <input type="submit" value="Create"> 
    </div>
</body>
</html>

单击上面的“创建”时得到的输出(到终端):

request.form.get('name') is Vinnie
in newTest(), request is POST
form does not validate
10.0.2.2 - - [18/Feb/2016 02:34:51] "POST /test/new/ HTTP/1.1" 200 -

然后浏览器重新显示表单及其内容。

我认为我错过了一些简单的事情,但我一生都无法弄清楚这一点。

代码的结构,如“树”所示,是:

code structure via tree

如果您有任何帮助,我将非常感激!

最佳答案

您是否尝试过在 HTML 文件中插入 CSRF token ?

例如,将以下内容添加到您的 Jinja 模板中?

<body>
    <div>
        <form action="{{ url_for('newTest') }}" method="POST" name="add_rest">
        <!-- Added line -->
        {{ form.csrf_token }}
        <ul>
            <li>Name: {{ form.name }}</li>
            <li>Address: {{ form.address }}</li>
        </ul>
        <input type="submit" value="Create"> 
    </div>
</body>

This SO帖子可能有用。

也可以查看官方文档here这表明 validate() 函数需要使用 CSRF token 。

关于python-2.7 - Flask WTForms 表单无法验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35472322/

相关文章:

python -\Z 与字符串结尾不匹配

Python Eve 包含过滤器

python-2.7 - python,检测到不一致的缩进

python-2.7 - 使用factory_boy和randint时生成重复值的问题

python - bson.errors.InvalidDocument : Cannot encode object: True

python - 测试 Flask-Restful 应用程序时随机出现 'werkzeug.routing.BuildError'

jquery - 如何将其他数据添加到AJAX文件上传中

python-3.x - 如何在 sqlAlchemy 中使用 "Like"运算符

Python SQLAlchemy 查询使用带有 ORM 的标记 OVER 子句

python - 通过主键传递列表作为参数从任意表加载记录