Question seen on Zhihu: Can python flask’s wtforms handle variable-length forms?
Problem description
form中的元素会变多。 比如有一个表格: 我喜欢的东西: 可以增加任意个物品(这几个物品填在不同的框),然后提交。 实现这个需求,需要用到FieldList
A simple example:
from wtforms import Form from wtforms.fields import FieldList, StringField class MyForm(Form): names = FieldList(StringField('名称'), label='物品列表', min_entries=1)
Submit form data:
names-0=苹果 names-1=梨 names-2=香蕉
Submit json data:
{"names": ["苹果", "梨", "香蕉"]}
Output result display:
print(form.names.data) # ['苹果', '梨', '香蕉']
The following is a more complicated example:
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)
Submit form data :
products-0-name=Iphone6 products-0-count=1 products-1-name=小米手机 products-1-count=2
Submit json data:
{"products": [{"name": "Iphone6", "count": 1}, {"name": "小米手机", "count": 2}]}
The output result shows:
print(form.products.data) # [{'name': 'Iphone6', 'count': 1}, {'name': '小米手机', 'count': 2}]
Then the question is, what is the key to dynamics?
That’s right, it’s the number starting with 0 in the field name you see
What should I do if I want to add an item?
The largest number plus 1, that’s it!
The js code in HTML is the key to achieving dynamics. The relevant code will not be shown. Here we only focus on the python part.