提交后清除有效表单

Clear valid form after it is submitted

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

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

问题是您总是使用传入的任何数据呈现表单,即使该数据已验证并已处理。此外,浏览器会存储上次请求的状态,因此如果此时刷新页面,浏览器将重新提交表单。

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

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

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

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

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)