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.
SubReddit
is 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
sr
function separately you can just combine it withindex()
and have the action in the form go tourl_for('index')
.