![](/img/trans.png)
[英]validate_on_submit always returns false using Flask WTForms
[英]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。
所以有很多問題。
將您的選擇更改為字符串:
choices=[('1', 'M'), ('2', "F")]
將您的表單方法更改為POST,因為validate_on_submit()
需要它:
<form action="" method="POST">
此外,要調試其他可能的錯誤(如CSRF),請將其添加到模板中:
{% if form.errors %} {{ form.errors }} {% endif %}
這為我修復了你的代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.