Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 %}
like image 210
Rafa Avatar asked Apr 06 '16 01:04

Rafa


People also ask

What does form Validate_on_submit do flask?

Validating Forms Note that you don't have to pass request. form to Flask-WTF; it will load automatically. And the convenient validate_on_submit will check if it is a POST request and if it is valid. If your forms include validation, you'll need to add to your template to display any error messages.

What is form Hidden_tag ()?

The form. hidden_tag() template argument generates a hidden field that includes a token that is used to protect the form against CSRF attacks. All you need to do to have the form protected is include this hidden field and have the SECRET_KEY variable defined in the Flask configuration.


1 Answers

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.

like image 61
wgwz Avatar answered Oct 20 '22 23:10

wgwz