gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:59:48 25 4
gpt4 key购买 nike

我有这个小 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 模板,我有:
{% 扩展 "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 %}

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

谢谢。

最佳答案

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

@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 中消失,所以你现在可能想开始使用它,你 future 的自己会感谢你!

关于python - 如何从使用 WTForm 构建的表单中清空数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26764197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com