在Flask中验证表单失败后如何保留输入 [英] How to keep input after failed form validation in flask

查看:108
本文介绍了在Flask中验证表单失败后如何保留输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用django,我可以在验证失败后将POST数据简单地传递给表单,而用户不必再次输入所有内容:

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?

推荐答案

与Flask类似,也是可能的:

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)

if表达式执行验证检查.如果验证成功,则将用户转发到登录页面.如果为假,将使用更新的表单作为参数再次调用 render_template ,因此该表单将与先前输入的数据一起再次显示(可能会提示需要修复的内容).

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).

代码摘自烧瓶文档.

这篇关于在Flask中验证表单失败后如何保留输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆