How to keep input after failed form validation in flask

若如初见. 提交于 2021-01-28 05:21:33

问题


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)
choice_form_set = ChoiceFormSet(request.POST)

How could I implement this on my own in flask?


回答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.



来源:https://stackoverflow.com/questions/44119600/how-to-keep-input-after-failed-form-validation-in-flask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!