Python 如何使用WTForms和flask验证数组?
我有一个提交数组的自定义表单:Python 如何使用WTForms和flask验证数组?,python,flask,flask-wtforms,Python,Flask,Flask Wtforms,我有一个提交数组的自定义表单: <form method="post" action="/doit"> <input type="text" name="mylist" value="one"> <input type="text" name="mylist" value="two"> <input type="text" name="mylist" value="three"> <input type="te
<form method="post" action="/doit">
<input type="text" name="mylist" value="one">
<input type="text" name="mylist" value="two">
<input type="text" name="mylist" value="three">
<input type="text" name="mylist" value="four">
</form>
如何构建WTForm,以便在验证表单时,
mylist
至少需要一项?通过阅读源代码,我得到了答案
表单侧:
class MyListForm(Form):
mylist = FieldList(StringField(validators=[]), validators=[])
好的..重要且令人困惑的是如何发布数据,以下是答案:
您的数据应该是这样的(python dict)
所有字段都有一个函数process(),用于获取自身的数据。普通类(如StringField、FloatField)是从字段实现的,字段列表有自己的process()函数,因为它需要迭代它的字段,它得到一个
\u extract\u index()函数要在提取索引的同时提取索引,请检查:
这就是它获取数据的方式
它需要键像“foo-0”,并且数据必须是列表
我不知道为什么没有在
我的第一个答案在这里,希望能有所帮助!!!:) 你能把表格代码寄出去吗?你使用的是<代码>字段列表字段吗?请考虑把这类问题作为注释,因为你是在问问题而不是回答……
{'mylist-0': ['one'], 'mylist-1': ['two'], 'mylist-2': ['three']}
def _extract_indices(self, prefix, formdata):
"""
Yield indices of any keys with given prefix.
formdata must be an object which will produce keys when iterated. For
example, if field 'foo' contains keys 'foo-0-bar', 'foo-1-baz', then
the numbers 0 and 1 will be yielded, but not neccesarily in order.
"""
offset = len(prefix) + 1
for k in formdata:
if k.startswith(prefix):
k = k[offset:].split('-', 1)[0]
if k.isdigit():
yield int(k)