烧瓶WTForms形式不验证 [英] Flask WTForms form does not validate

查看:216
本文介绍了烧瓶WTForms形式不验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获得一个简单的Flask WTForm来验证。

经过几天的努力,我尝试了所有我能想到的。我是一般的Flask和Web编程的新手。



这是我的代码的精简但工作版本。测试代码(除了提交表单)的唯一行为是将消息打印到终端。它运行时的外观:





这是views .py:

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

@ app.route('/ test / new /',methods = ['GET','POST'])
def newTest():$ b $ form = TestForm(request.form)
if form:
print'request.form.get(\'name \')is%s'%(request.form.get('name'),)
if request。方法=='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:
返回render_template('newTest.html ,form = form)

这里是forms.py:

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

submit = SubmitField(uSubmit)

models.py:

  from sqlalchemy import列,整型,Unicode 
from sqlalchemy.ext.declarative import declarative_base
$ b Base = declarative_base()
$ b $ 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>新测试< / title>
< / head>
< body>
< div>
< form action ={{url_for('newTest')}}method =POSTname =add_rest>
< ul>
< li>名称:{{form.name}}< / li>
< li>地址:{{form.address}}< / li>
< / ul>
< input type =submitvalue =Create>
< / div>
< / body>
< / html>

当我点击上面的创建时,输出(到终端):

  request.form.get('name')是在newTest()中的Vinnie 
,request是POST
表单不验证
10.0.2.2 - - [18 / Feb / 2016 02:34:51]POST / test / new / HTTP / 1.1200 -

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

我假设我错过了简单的东西,但是我一直没能弄明白我的生活。
$ b

代码的结构,如tree所示:



我会非常感谢任何帮助!

解决方案



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

>

 < body> 
< div>
< form action ={{url_for('newTest')}}method =POSTname =add_rest>
<! - 增加了一行 - >
{{form.csrf_token}}
< ul>
< li>名称:{{form.name}}< / li>
< li>地址:{{form.address}}< / li>
< / ul>
< input type =submitvalue =Create>
< / div>
< / body>

这个SO 文章可能是有用的。



您也可以查看官方文档这里表示 validate()函数需要使用CSRF令牌。

I cannot get a certain simple Flask WTForm to validate.

After a couple of days of struggle, I've tried everything I can think of. I'm new to Flask and Web programming in general.

Here's a stripped-down but working version of my code. The only action of the test code (other than submitting the form) is to print messages to terminal. Its appearance when running:

This is 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)

Here's forms.py:

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

    submit = SubmitField(u"Submit")

models.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)

and the template:

<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>

The output (to terminal) I get when I click "Create" above:

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 -

then the browser redisplays the form and its contents.

I assume I'm missing something simple, but I haven't been able to figure this out for the life of me.

The structure of the code, as shown by "tree", is:

I'd be very grateful for any help!

解决方案

Have you tried to insert a CSRF token in your HTML file?

For example, by adding the following to your Jinja template?

<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 post may be useful.

You can also check the official documentation here which indicates that the validate() function requires the use of a CSRF token.

这篇关于烧瓶WTForms形式不验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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