Question about how WTForms process variable-length forms: can python flask wtforms process variable-length forms?
Problem Description
There will be more elements in form. For example, there is a table: my favorite items: any items can be added (these items are entered in different boxes), and then submitted. FieldList is required to meet this requirement.
A simple example:
From wtforms import Formfrom wtforms. fields import FieldList, StringFieldclass MyForm (Form): names = FieldList (StringField ('name'), label = 'item list', min_entries = 1)
Submit form data:
Names-0 = Apple names-1 = pear names-2 = banana
Submit json data:
{"Names": ["apple", "pear", "banana"]}
Output result:
Print (form. names. data) # ['apple', 'PE', 'banana ']
The following is a more complex example:
From wtforms import Formfrom wtforms. fields import FieldList, FormField, StringField, IntegerFieldclass ProductForm (Form): name = StringField ('name') count = IntegerField ('number') class MyForm (Form ): products = FieldList (FormField (ProductForm), label = 'product list', min_entries = 1)
Submit form data:
Products-0-name = Iphone6products-0-count = 1products-1-name = Xiaomi phone products-1-count = 2
Submit json data:
{"Products": [{"name": "Iphone6", "count": 1 },{ "name": "Xiaomi phone", "count": 2}]}
Output result:
Print (form. products. data) # [{'name': 'iphone6', 'count': 1}, {'name': 'Xiaomi cell phone ', 'count': 2}]
So 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 one?
The biggest number plus 1 is it!
In html, js code is the key to dynamic implementation, and relevant code is not displayed. here we only focus on the python part.