Flask wtform forms.validate_on_submit() is always false

user3743022 picture user3743022 · Jun 15, 2014 · Viewed 8.7k times · Source

I have looked at other similar problems on here and a few other places, but the solutions don't seem to help with my problem. Even though, I am not seeing too much of a difference between this simple code that I've got and other similar code. Especially this one Flask - wtforms: Validation always false

forms.validate_on_submit() is always false and I can't see why. I'm going through the Flask Web Development Book by Miguel Grinberg, but I wanted to change some things in order to learn more. It works when using the wtf.quick_form(form) in the html template, but if I remove the quickform entry and put in form fields , then it doesn't work The screen just refreshes and it doesn't change Stranger to whatever name is entered

HTML index template

 {% extends "base.html" %}
 {% import "bootstrap/wtf.html" as wtf %}

 {% block title %}Flasky{% endblock %}

 {% block page_content %}
 <div class="page-header">
     <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>

 </div>
 <form action="" method='POST'>

  {{ form.name.label }} <br>
  {{ form.name }}
{{ form.submit }}
</form>
{% endblock %}

relevant code hello.py

from flask import Flask, render_template, request
from flask.ext.script import Manager
from flask.ext.bootstrap import Bootstrap
from flask.ext.moment import Moment
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, RadioField, TextField, validators
from wtforms.validators import Required
from wtforms.validators import DataRequired

app = Flask(__name__)



class NameForm(Form):
    name = StringField('What is your name?',validators=[Required()] )

submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
     name = None
     form = NameForm(request.form)  #From the docs I read I don't need 
                                    # request.form but it
                                    # doesn't work either with it or without it

     if form.validate() == True:
      name='True'  #never happens  is not validating or is always set to False for 
                       # some reason

     if form.validate_on_submit(): #isn't validating or working
          name = form.name.data  #'Stranger' will disappear from the html template and 
                            #replaced   with the name the user entered in the
                            # Stringfield 

          form.name.data = ''  #clear stringfield for next round

          return render_template('index.html',form=form, name=name)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80, debug=True)'

what am I not understanding\missing? Thanks

g

Answer

Bernard Ojengwa picture Bernard Ojengwa · Oct 8, 2014

The problem is with wtf not finding the CSRF Tokens as part of your form data. Add {{ form.hidden_tag() }} or {{ form.csrf_token }} as the top element of your form.