我正在努力弄清楚如何完成与表中另一个元素关联的唯一表单字段实例。下面是一个人为的例子:
from flask import Flask, render_template, request
from flask.ext.wtf import Form
from wtforms import TextField, BooleanField
app = Flask(__name__)
app.debug = True
app.config['SECRET_KEY'] = 'secret'
class Person(Form):
fname = TextField('First Name')
phone = TextField('Phone Number')
email = TextField('Email Address')
active = BooleanField('Active')
@app.route("/", methods=['GET', 'POST'])
def guest():
names = ['Bob', 'Joe', 'Jason', 'John'] # this could be a list, or data returned from a db query, previous POST data, or whatever
form = Person()
if request.method == 'POST' and form.validate_on_submit():
return str(form.data)
return render_template('index.html', names=names, form=form)
if __name__ == "__main__":
app.run(host='0.0.0.0')
我的模板:
<html>
<body>
<form action="" method="post">
<table border="1">
<thead>
<tr>
<th>Name</th>
<th>Telephone Number</th>
<th>Email Address</th>
<th>Active</th>
</tr>
</thead>
<tbody>
{% for n in names %}
<tr>
<td>{{ n }}</td>
<td>{{ form.phone }}</td>
<td>{{ form.email }}</td>
<td>{{ form.active }}</td>
</tr>
{% endfor %}
</tbody>
</table>
很明显,在 HTML 中,name每个表格行中每个输入元素的参数都是相同的,因为正在使用相同的表单字段,因此在“POST”中,如果输入电话号码,该电话号码现在将填充到表格中的所有名称行。 “激活”复选框也是如此。我还尝试生成一个表单实例列表并将该列表传递到模板中,但它似乎没有像我预期的那样工作。在这一点上我的选择似乎是:
- 不要为此使用 WTForms(请参阅下面的注释)
- 使用 WTForms FieldList + FormField(我认为这也行不通,因为它们需要命名键而不是任意键,所以我会遇到完全相同的问题。)
- 以某种方式使用 HiddenFields(甚至没有想过它是如何工作的)。
我知道我可以创建 <input type>通过模板手动将元素添加到表中,并根据 w 为它们分配不同的名称/ID但这感觉不太习惯,而且我必须自己编写验证代码。
请您参考如下方法:
您通常会传入一个包含表单数据的多字典对象作为表单的第一个参数:
form = UpdateWidgetForm(request.form)
这确实需要 POST 数据与表单中的小部件相匹配;每个小部件将检查该 multi-dict 并提取它需要使用一些预填充数据呈现的内容。
或者,您可以将值作为关键字参数传递,但这确实需要您自己验证输入,将任何值转换为正确的类型:
number = request.form.get('widget_number')
try:
number = int(number)
except ValueError:
abort(404)
policy = request.form.get('widget_policy')
if policy not in ('foo', 'bar'):
abort(404)
form = UpdateWidgetForm(widget_number=number, widget_policy=policy)
参见 How Forms get data在文档中。
如果您需要在一个页面中生成多个表单,每个表单都是唯一的,来自同一个表单对象,您需要使用 Form(prefix=..) 参数为每个表单指定一个唯一的前缀。
