Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting on Form Validation Failure (Flask-WTForms)

I'm trying to use Flask-WTF for a new form that I'm adding to a Flask app that I recently inherited. I'm fairly new to the Flask ecosystem (completely new to WTForms), and I haven't done any web development in four years.

Example code in the Flask-WTF documentation renders a page on form validation failure, rather than redirecting (Post/Redirect/Get). At that point, a browser refresh would resubmit the previous POST. This isn't good, right? While most folks don't seem to give this scenario any attention, I do see a few people who feel like this is something to avoid (e.g. here and here).

So how would I avoid this issue while using Flask-WTF? If I redirect on validation failure, I think I lose the ability to show validation errors on each field. Or perhaps I shouldn't worry about this scenario?

like image 689
Neal Gokli Avatar asked Oct 30 '22 06:10

Neal Gokli


1 Answers

Personally never felt like this was an issue. I use Flask-WTF w/ Flask-Bootstrap and it highlights form field errors for me on a failed validation. If they try and resubmit the form it will fail again and never reaches the database level so you don't have to worry about the issue Post/Redirect/Get is trying to solve.

@app.route('/', methods=['GET', 'POST'])
def index():
    form = MyForm()
    if form.validate_on_submit():
        # add/update db. if form is invalid you never get here
        return redirect(url_for('success'))
    return render_template('index.html', form=form)
like image 141
Adam Avatar answered Dec 31 '22 14:12

Adam