成功提交表单后电子邮件字段未清除

Email field not clearing on successful form submit

我在 Flask WTF 中的表单有两个字段:姓名和电子邮件。当我成功提交表单时,名称字段被重置,而电子邮件字段保留其值。到目前为止,浏览器的行为是相同的(我已经在 Chrome 和 Firefox 上试过了)。以下是我的意思的屏幕截图:

以下是相关的代码片段:

class NameForm(Form):
    name = StringField('What is your name?', validators=[Required()])
    email = StringField('What is your email?', validators=[Required(), Email()])
    submit = SubmitField('Submit')

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()
    if form.validate_on_submit():
        name = form.name.data
    return render_template('index.html', form=form, name=name)

{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}

{% block title %}Flasky{% endblock %}

{% block page_content %}
<div class="page-header">
    <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}

知道是什么导致了这种行为吗?

表单永远不会被清除,因为无论如何您都会将填好的表单传回模板。由于响应是 post 请求的一部分,浏览器还会在内部记住表单的状态(如果刷新,您会收到一条 "are you sure you want to resubmit?" 消息)。

常见的模式是在 post 填写表单后重定向,以清除呈现状态和有关已提交表单的任何保存的浏览器状态。您通常需要在 post 处理表单后存储状态,因此您可以使用数据库,或者在本示例中将其简单地存储在会话中。

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

    if form.validate_on_submit():
        session['name'] = form.name.data
        return redirect(url_for('index'))

    return render_template('index.html', form=form, name=session.get('name'))