I know that there are similar problems which have been answered. The csrf_enabled
is not an issue now if the Form
inheriting FlaskForm
, and the template has the form.hidden_tag()
.
I have the following flask app.
## 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)
The following is index.html template:
<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>
After clicking the submit
button the execution never goes in the if form.validate_on_submit()
block in the index
function.
I also removed all the validators, the code inside validate_on_submit
block is still unreachable. Printing form.validate_on_submit()
is always false.
So there are multiple problems.
Change your choices to strings:
choices=[('1', 'M'), ('2', "F")]
Change your form method to POST, because validate_on_submit()
requires it:
<form action="" method="POST">
Additionally, to debug other possible errors (like CSRF), add this to your template:
{% if form.errors %}
{{ form.errors }}
{% endif %}
That fixed your code for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With