问题描述
form中的元素会变多。 比如有一个表格: 我喜欢的东西: 可以增加任意个物品(这几个物品填在不同的框),然后提交。 实现这个需求,需要用到FieldList
一个简单的例子 :
from wtforms import Form
from wtforms.fields import FieldList, StringField
class MyForm(Form):
names = FieldList(StringField('名称'), label='物品列表', min_entries=1)提交表单数据:
names-0=苹果 names-1=梨 names-2=香蕉
提交json数据:
{"names": ["苹果", "梨", "香蕉"]}输出结果显示:
print(form.names.data) # ['苹果', '梨', '香蕉']
下面是再复杂一点的例子:
from wtforms import Form
from wtforms.fields import FieldList, FormField, StringField, IntegerField
class ProductForm(Form):
name = StringField('名称')
count = IntegerField('数量')
class MyForm(Form):
products = FieldList(FormField(ProductForm), label='产品列表', min_entries=1)提交表单数据:
products-0-name=Iphone6 products-0-count=1 products-1-name=小米手机 products-1-count=2
提交json数据:
{"products": [{"name": "Iphone6", "count": 1}, {"name": "小米手机", "count": 2}]}输出结果显示:
print(form.products.data)
# [{'name': 'Iphone6', 'count': 1}, {'name': '小米手机', 'count': 2}]那么问题来了,动态的关键是什么?
没错,就是你看到的字段名称中的以0开始的数字啊
想要加一项怎么办?
最大的数字加1,就是它!
那在html中js代码是实现动态的关键,相关代码就不展示了,这里只关注python的部分。
下载本文