如何清空使用WTForm构建的表单中的数值

时间:2014-11-05 18:13:43

标签: python flask flask-wtforms

我有这个小型Flask程序。它期望用户的姓名和年龄,然后它打印一条消息。非常简单,因为我刚刚开始使用Python和Flask。

from flask import Flask, render_template
from flask.ext.bootstrap import Bootstrap 
from flask.ext.wtf import Form 
from wtforms import StringField, IntegerField, SubmitField
from wtforms.validators import Required, Length, NumberRange

app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
bootstrap = Bootstrap(app)

class NameForm(Form):
    name = StringField('What is your name?', validators = [Required(), Length(1, 16)])
    age  = IntegerField('How old are you?', validators = [Required(), NumberRange(min=1, max=99, message="Should be between 1 and 99")])

    submit = SubmitField('Submit')

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

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

if __name__ == '__main__':
    app.run(debug = True)

而且,对于HTML模板,我有:     {%extends" bootstrap / base.html" %}

{% block title %}Form Example{% endblock %}

{% block navbar %}
    <nav class="navbar navbar-inverse" role="navigation">
        <div class="container">
            <a href="{{ url_for('index') }}" class="navbar-brand">Hello</a>
        </div>
    </nav>
{% endblock %}

{% block content %}
    <div class="container">
        <form method="POST" action="">
            {{ form.name.label }} {{ form.name(size=16, class='name-field') }}
            {% for error in form.name.errors %}
                {{ error }}
            {% endfor %}

            <br>

            {{ form.age.label }} {{ form.age(class='age-field') }}
            {% for error in form.age.errors %}
                {{ error }}
            {% endfor %}

            <br />
            {{ form.submit() }}
            {{ form.hidden_tag() }}
        </form>
        {% if name %}
            <h1>Hello, {{ name.capitalize() }}</h1>
            <h2>You're {{ age }} years old.</h2>
        {% endif %}
    </div>
{% endblock %}

我的问题是,在我提交表单后,名称输入被清空但年龄输入不是。为什么?如何清空数字字段?

感谢。

1 个答案:

答案 0 :(得分:4)

感谢明确的问题 - 我能想到的最简单的方法就是创建它并告诉它忽略请求表单数据。

@app.route('/', methods=['GET', 'POST'])
def index():
    form = NameForm()  # Auto-populates from request data.
    name = None
    age = None
    if form.validate_on_submit():
        name = form.name.data
        age  = form.age.data

        # Lets now create a form, but ignore the request data, so it's empty:
        form = NameForm(formdata=None)
    return render_template('index.html', form = form, name = name, age = age)

此外,我注意到您正在使用Required()正在被DataRequired()取代,并且将在WTF v3中消失,因此您可能想立即开始使用它,您的未来将会感谢你!