0

My form in Flask WTF has two fields: name and email. When I submit the form successfully, the name field gets reset while the email field retains its values. The behavior is the same across browsers (I've tried it on Chrome and Firefox) so far. Here are screen shots for what I mean:

enter image description here

enter image description here

enter image description here

Here are the relevant code snippets:

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 %}

Any idea what's causing this behavior?

davidism
  • 121,510
  • 29
  • 395
  • 339
ankush981
  • 5,159
  • 8
  • 51
  • 96

1 Answers1

2

The form never gets cleared because you are passing it filled in back to the template no matter what. Since the response is part of a post request, the browser also internally remembers the state of the form (you'd get a "are you sure you want to resubmit?" message if you refreshed).

The common pattern is to redirect after posting a form, to clear both the render state and any saved browser state about the submitted form. You usually need to store state from the form after posting it, so you would use a database, or simply store it in the session for this example.

@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'))
davidism
  • 121,510
  • 29
  • 395
  • 339