I am having trouble wrapping my head around the logic of flask routing. For example, the snippet below could handle a registration form. The tricky (for me) part is that the form.validate_on_submit()
logic is before the template rendering. That is, when a user gets the chance to submit something in the form, the function is already in the return statement, past the form.validate_on_submit()
logic.
Nevertheless, it this example still works. I would like to understand how can the logic in the function be executed even after its return statement has been reached.
@app.route('/', methods=('GET', 'POST'))
def contact():
form = ContactForm()
if form.validate_on_submit():
return redirect(url_for('success'))
return render_template('index.html', form=form)
Thanks!
The key concept here is the if
conditional.
What you are missing out on is the fact that form.validate_on_submit
is a convenience function which is equivalent to saying
if request.method=="POST" and form.validate():
# ...
You can see an example where this is shown here
When the page is first loaded, it is with a GET request. We execute the first line form = ContactForm()
and, since our conditional does not evaluate to True which it will not since it is not a POST request, we go to the last line and render the HTML template, passing in the form.
Now, once the page is displayed to the user and they submit the form, we send a request to the same route as before, but with a POST request. Now, we can validate the form and assuming everything checks out, we can fire off the redirect.
Hope that help, it can definitely be a bit confusing before you really get comfortable with what you're looking at!