问题
I have the following code and I'm submitting a form. When I hit the submit button, my form validation prints out False
. I've checked and made sure I'm including everything from different posts, but I can't get it to validate. Is there anything I'm doing wrong?
@app.route('/index.html', methods=['GET', 'POST'])
def index():
user = {'nickname': 'Rafa'}
form = FilterForm()
print("about to validate", file=sys.stderr)
if form.validate_on_submit():
print("validated", file=sys.stderr)
filters_array = form.filter.split(',')
streaming(filters_array)
response = {"response", "yes"}
redirect("/authenticate")
return render_template('index.html',
title="Home",
user=user,
form=form)
class FilterForm(Form):
filter = StringField('filter', validators=[DataRequired()])
Here is my Jinja file
{% block content %}
<h1> I have successfully navigated to the title pagee </h1>
<h1> Hello, {{user.nickname}}!</h1>
<h1> Get Tweets </h1>
<p> Please enter a comma delimited list of filters</p>
<form action="" method="post" name="login">
{{form.filter(size=80)}}
<input type="submit" value="Get Tweets!">
</form>
{% endblock %}
回答1:
FilterForm
should not be indented at the same level as def index()
. More importantly, you don't have a csrf_token
in your form. Which will prevent it from validating.
Add this to your form:
{{ form.csrf_token }}
Lastly, when validating with wtforms, the errors are populated in the form object. So after an if validate
, try printing form.errors
and you'll find out exactly what is wrong.
回答2:
I have found some syntax error in your code, maybe that will cause the problem you have met.
first, the problem in your decorator app.route:
app.route('/index')
second, in your html file:
form action='/index'
回答3:
Another requirement is that when you use form.validate_on_submit
, you have to make sure that you had use all fields of your form model.
来源:https://stackoverflow.com/questions/36440003/wtf-form-validate-on-submit-not-working