繁体   English   中英

Flask validate_on_submit始终为False

[英]Flask validate_on_submit always False

我知道有类似的问题已得到解答。 csrf_enabled现在不是一个问题,如果Form继承FlaskForm和模板具有form.hidden_tag()

我有以下烧瓶应用程序。

## Filenname: app.py

from flask import Flask, render_template, redirect, url_for, flash, request
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, SelectField
from wtforms.validators import DataRequired

app = Flask(__name__)

app.config["SECRET_KEY"] = "secret"



class DataForm(FlaskForm):
    name = StringField("Name", validators=[DataRequired()])
    gender = SelectField("Gender", validators=None, choices=[(1, 'M'), (2, "F")])
    submit = SubmitField("Submit", validators=None)



@app.route('/index', methods=["GET", "POST"])
def index():
    form = DataForm(request.form)
    print(form.validate_on_submit())
    if form.validate_on_submit():
        print(form.validate())
        print(form.name)
        flash("THIS IS FLASH")
        title="hello"
        return redirect(url_for('output'))
    return render_template('index.html', form=form)



@app.route('/output', methods=["GET", "POST"])
def output():
    title = "hello"
    form = DataForm()
    print(form.validate())
    return render_template('output.html', title=title)


app.run(debug=False)

以下是index.html模板:

<html>
    <body>
        {% with messages = get_flashed_messages() %}
        {{ messages }}
        {% endwith %}



        <form action="" method="GET">
            {{ form.hidden_tag() }}
            {{ form.name.label }}
            {{ form.name() }}
            {% for error in form.name.errors %}
            <span style="color: red;">[{{ error }}]</span>
            {% endfor %}

            <hr>

            {{ form.gender.label }}
            {{ form.gender() }}

            {{ form.submit() }}
        </form>
    </body>
</html>

单击submit按钮后,执行永远不会进入index函数中的if form.validate_on_submit()块。

我还删除了所有验证器, validate_on_submit块中的代码仍然无法访问。 打印form.validate_on_submit()始终为false。

所以有很多问题。

  1. 将您的选择更改为字符串:

     choices=[('1', 'M'), ('2', "F")] 
  2. 将您的表单方法更改为POST,因为validate_on_submit()需要它:

     <form action="" method="POST"> 
  3. 此外,要调试其他可能的错误(如CSRF),请将其添加到模板中:

     {% if form.errors %} {{ form.errors }} {% endif %} 

这为我修复了你的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM