WTF form.validate_on_submit() not working

匆匆过客 提交于 2020-07-09 06:13:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!