flask-wtf form validation not working for my new app
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping
--
Chapters
00:00 Flask-Wtf Form Validation Not Working For My New App
01:37 Answer 1 Score 3
02:14 Accepted Answer Score 13
03:33 Thank you
--
Full question
https://stackoverflow.com/questions/1773...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask #flaskwtforms
#avk47
ACCEPTED ANSWER
Score 13
You have a number of problems.
The most important is that validation occurs in the POST request view function. In your example this is function sr. That function should create the form object and validate it before adding stuff to the database.
Another problem in your code (assuming the above problem is fixed) is that after validate fails you redirect. The correct thing to do is to render the template right there without redirecting, because the error messages that resulted from validation are loaded in that form instance. If you redirect you lose the validation results.
Also, use validate_on_submit instead of validate as that saves you from having to check that request.method == 'POST'.
Example:
@app.route('/sr', methods=['POST'])    
def sr():
    form = subReddit()
    if not form.validate_on_submit():
        return render_template('index.html',form=form)
    g.db.execute("UPDATE subreddit SET sr=(?)", [form.subreddit.data])      
    return redirect(url_for('index'))
Additional suggestions:
- it is common practice to start your class names with an upper case character. 
SubRedditis better thansubReddit. - it is also common to have the GET and POST request handlers for a form based page in the same view function, because that keep the URLs clean when validation fails without having to jump through hoops to get redirects working. Instead of having the 
srfunction separately you can just combine it withindex()and have the action in the form go tourl_for('index'). 
ANSWER 2
Score 3
Flask-WTF adds a new method onto the form called validate_on_submit(). This is like the WTForms validate() method, but hooks into the Flask framework to access the post data. The example given on the Flask site is:
form = MyForm()
if form.validate_on_submit():
    flash("Success")
    return redirect(url_for("index"))
return render_template("index.html", form=form)
Because you're just using validate(), the form is trying to validate without any data (which, of course, will fail). Then you're redirecting. Try to use validate_on_submit() as shown above.