Home > Backend Development > Python Tutorial > [Python] Use WTForms to process variable-length forms

[Python] Use WTForms to process variable-length forms

大家讲道理
Release: 2016-11-07 10:20:33
Original
1879 people have browsed it

Question seen on Zhihu: Can python flask’s wtforms handle variable-length forms?

Problem description

form中的元素会变多。
比如有一个表格:
我喜欢的东西: 可以增加任意个物品(这几个物品填在不同的框),然后提交。
实现这个需求,需要用到FieldList
Copy after login

A simple example:

from wtforms import Form
from wtforms.fields import FieldList, StringField
class MyForm(Form):
    names = FieldList(StringField('名称'), label='物品列表', min_entries=1)
Copy after login

Submit form data:

names-0=苹果
names-1=梨
names-2=香蕉
Copy after login

Submit json data:

{"names": ["苹果", "梨", "香蕉"]}
Copy after login

Output result display:

print(form.names.data)
# ['苹果', '梨', '香蕉']
Copy after login

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)
Copy after login

Submit form data :

products-0-name=Iphone6
products-0-count=1
products-1-name=小米手机
products-1-count=2
Copy after login

Submit json data:

{"products": [{"name": "Iphone6", "count": 1}, {"name": "小米手机", "count": 2}]}
Copy after login

The output result shows:

print(form.products.data)
# [{'name': 'Iphone6', 'count': 1}, {'name': '小米手机', 'count': 2}]
Copy after login

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.


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template