获取通过wtform字段迭代的数据

3 投票
2 回答
2339 浏览
提问于 2025-04-18 08:05

我有一个表单,里面有一些动态添加的字段。

class EditBook(Form):
    title = TextField('title', validators = [Required()])
    authors = FieldList(TextField())

这是我添加这些字段的方法。

$('form').append('<input type="text" class="span4" id="authors-' + FieldCount +'" name="authors-' + FieldCount +'" placeholder="author ' + FieldCount +'">');

我想从这些输入框中获取数据。请问我该如何用Python遍历它们呢?

(或者我该如何用jQuery把收集到的数据发送到服务器?我对JavaScript和jQuery还不太熟悉)

我猜我的输入框没有和作者的字段列表连接起来。

更新

虽然我把输入框添加到了EditBook,但它们还是没有连接上。

当我把输入框附加到表单时,form.data会解决剩下的问题。(现在我尝试访问form.data['authors-1']时出现了keyerror)

现在我试着只添加一个作者字段,以便之后可以复制它。

但是这个字段却看不见,原因不明。

在空白的地方应该有一个输入框,类似于“author-1”。

{{form.authors(class="span4", placeholder="author 1")}}

我应该在代码中添加什么才能正确显示这个字段呢?

2 个回答

0

Form对象是可以被遍历的,它会返回它里面的字段,具体用法如下:

for f in form:
  print(f"{f.id}: {f.data}")
1

WTFormsprocess_formdata 方法会从表单提交的数据中提取信息,并把这些信息存储在 data 属性里。下面是你访问这些数据时的代码示例。你的 authors 列表应该存放在一个可以遍历的结构中,这样你就可以通过 authors 这个键来访问它。

from collections import namedtuple
from wtforms.validators import Required
from wtforms import Form
from wtforms import TextField
from wtforms import FieldList

from webob.multidict import MultiDict

class EditBook(Form):
    title = TextField('title', validators = [Required()])
    authors = FieldList(TextField())

Book = namedtuple('Book', ['title', 'authors'])
b1 = Book('Title1', ['author1', 'author2'])

# drop them in a dictionary 
data_in={'title':b1.title, 'authors':b1.authors}

# Build form and print
form = EditBook(data=MultiDict(data_in))

# lets get some data
print form.data
print form.data['title']
print form.data['authors']

撰写回答