【问题标题】:Flask validate_on_submit always False烧瓶 validate_on_submit 总是 False
【发布时间】:2018-01-26 04:09:37
【问题描述】:

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

我有以下烧瓶应用程序。

## 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() 总是错误的。

【问题讨论】:

标签: python flask jinja2


【解决方案1】:

所以有多个问题。

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

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

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

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

这为我修复了您的代码。

【讨论】:

  • 我也尝试过"POST""POST" 是正确的方法)。主要问题是选择,而不是使用整数 1 应该使用字符串 '1' 正如您所指出的那样
【解决方案2】:
  1. 只需制作表格即可,无需

2.form = FlaskForm(meta={'csrf': False})

【讨论】:

    猜你喜欢
    • 2020-12-24
    • 2020-07-24
    • 1970-01-01
    • 2013-12-08
    • 2013-09-14
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2021-12-04
    相关资源
    最近更新 更多