Skip to content Skip to sidebar Skip to footer

How To Keep Input After Failed Form Validation In Flask

With django I could simply pass the POST data to the form after failed validation and the user would not have to enter everything again: question_form = QuestionForm(request.POST)

Solution 1:

It's pretty similarly possible with Flask as well:

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm(request.form)
    if request.method == 'POST' and form.validate():
        user = User(form.username.data, form.email.data,
                    form.password.data)
        db_session.add(user)
        flash('Thanks for registering')
        return redirect(url_for('login'))
    return render_template('register.html', form=form)

The if expression performs the validation check. If validation is successful, the user is forwarded to the login page. If it's false, render_template is called again with the updated form as parameter, so the form is displayed again with the previously entered data (possibly with hints on what needs to be fixed).

Code taken from Flask documentation.

Post a Comment for "How To Keep Input After Failed Form Validation In Flask"