[Python]使用WTForms處理可變長的表單

來源:互聯網
上載者:User
在知乎上看到的問題:python flask的wtforms可以處理可變長的表單嗎?

問題描述

form中的元素會變多。比如有一個表格:我喜歡的東西: 可以增加任意個物品(這幾個物品填在不同的框),然後提交。實現這個需求,需要用到FieldList

一個簡單的例子 :

from wtforms import Formfrom wtforms.fields import FieldList, StringFieldclass MyForm(Form):    names = FieldList(StringField('名稱'), label='物品列表', min_entries=1)

提交表單資料:

names-0=蘋果names-1=梨names-2=香蕉

提交json資料:

{"names": ["蘋果", "梨", "香蕉"]}

輸出結果顯示:

print(form.names.data)# ['蘋果', '梨', '香蕉']

下面是再複雜一點的例子:

from wtforms import Formfrom wtforms.fields import FieldList, FormField, StringField, IntegerFieldclass ProductForm(Form):    name = StringField('名稱')    count = IntegerField('數量')class MyForm(Form):    products = FieldList(FormField(ProductForm), label='產品列表', min_entries=1)

提交表單資料:

products-0-name=Iphone6products-0-count=1products-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的部分。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.