WTF form.validate_on_submit() 不工作

WTF form.validate_on_submit() not working

我有以下代码并且正在提交表单。当我点击提交按钮时,我的表单验证打印出 False。我已经检查并确保我包含了来自不同帖子的所有内容,但我无法对其进行验证。我做错了什么吗?

@app.route('/index.html', methods=['GET', 'POST'])
    def index():   
            user = {'nickname': 'Rafa'}
            form = FilterForm()
            print("about to validate", file=sys.stderr)
            if form.validate_on_submit():
                    print("validated", file=sys.stderr)
                    filters_array = form.filter.split(',')
                    streaming(filters_array)
                    response = {"response", "yes"}
                    redirect("/authenticate")



            return render_template('index.html',
                    title="Home",
                    user=user,
                    form=form)

    class FilterForm(Form):
            filter = StringField('filter', validators=[DataRequired()])

这是我的 Jinja 文件

    {% block content %}    
      <h1> I have successfully navigated to the title pagee </h1> 
      <h1> Hello, {{user.nickname}}!</h1> 
      <h1> Get Tweets </h1> 
      <p> Please enter a comma delimited list of filters</p>   
      <form action="" method="post" name="login"> 
        {{form.filter(size=80)}} 
      <input type="submit" value="Get Tweets!"> 
      </form> 
    {% endblock %}

FilterForm 不应与 def index() 缩进同一级别。更重要的是,您的表单中没有 csrf_token。这将阻止它验证。

将此添加到您的表单中:

{{ form.csrf_token }}

最后,在使用 wtforms 进行验证时,错误会填充到表单对象中。所以在 if validate 之后,尝试打印 form.errors ,你会发现究竟是什么地方出了问题。

我在你的代码中发现了一些语法错误,也许这会导致你遇到的问题。

首先是你装饰器的问题app.route:

app.route('/index')

其次,在您的 html 文件中:

form action='/index'

另一个要求是,当您使用 form.validate_on_submit 时,您必须确保您已经使用了表单模型的所有字段。