提交后清除有效表格

时间:2015-08-11 15:00:23

标签: python flask wtforms flask-wtforms

我希望在验证后重置表单。目前,表单在提交并有效后仍会显示以前的数据。基本上,我希望表单恢复到原始状态,所有字段都清理干净。这样做的正确性是什么?

@mod.route('/', methods=['GET', 'POST'])
def home():
    form = NewRegistration()

    if form.validate_on_submit():
        #save in db

        flash(gettext(u'Thanks for the registration.'))

    return render_template("users/registration.html", form=form)

2 个答案:

答案 0 :(得分:19)

问题在于,您始终使用传入的任何数据呈现表单,即使该数据已经过验证和处理。此外,浏览器存储最后一个请求的状态,因此如果此时刷新页面,浏览器将重新提交表单。

处理成功的表单请求后,重定向到页面以获得新的状态。

@app.route('/register', methods=['GET', 'POST'])
def register():
    form = RegistrationForm()

    if form.validate_on_submit():
        # do stuff with valid form
        # then redirect to "end" the form
        return redirect(url_for('register'))

    # initial get or form didn't validate
    return render_template('register.html', form=form)

答案 1 :(得分:0)

大卫主义的答案是正确的。

但是一旦我不得不重新加载一个只有几个必须重置的字段的表单。 所以,我这样做了,也许这不是最干净的方法,但是对我有用:

form = MyForm()

    if form.validate_on_submit():
        # save all my data...
        myvar1 = form.field1.data
        myvar2 = form.field2.data
        # etc...

    # at first GET and at every reload, this is  what gets executed:
    form.field1.data = "" # this is the field that must be empty at reload
    form.field2.data = someobject # this is a field that must be filled with some value that I know

    return render_template('mypage.html', form=form)