Search code examples
flaskwtformsflask-wtforms

WTF form.validate_on_submit() not working


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 %}

Solution

  • 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.