[Python] using WTForms to process variable-length forms

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.