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