使用动态数量的字段制作 Django 表单类 [英] Making a Django form class with a dynamic number of fields
问题描述
我正在开发类似在线商店的东西.我正在制作一个客户购买商品的表格,她可以选择她想要购买的商品数量.但是,在她购买的每件商品上,她都需要选择它的颜色.所以有一个非恒定数量的字段:如果客户购买 3 件商品,她应该得到 3 个 框来选择颜色,如果她购买 7 件商品,她应该得到 7 个这样的 <代码><选择> 框.
我将使用 JavaScript 使 HTML 表单字段出现和消失.但是我如何在我的 Django 表单类中处理这个问题?我看到表单字段是类属性,所以我不知道如何处理某些表单实例应该有 3 个颜色字段和一些 7 个的事实.
有什么线索吗?
Jacob Kaplan-Moss 有大量关于动态表单字段的文章:http://jacobian.org/writing/dynamic-form-generation/>
本质上,您可以在实例化过程中向表单的 self.fields
字典中添加更多项.
I'm working on something like an online store. I'm making a form in which the customer buys an item, and she can choose how many of these item she would like to buy. But, on every item that she buys she needs to choose what its color would be. So there's a non-constant number of fields: If the customer buys 3 items, she should get 3 <select>
boxes for choosing a color, if she buys 7 items, she should get 7 such <select>
boxes.
I'll make the HTML form fields appear and disappear using JavaScript. But how do I deal with this on my Django form class? I see that form fields are class attributes, so I don't know how to deal with the fact that some form instance should have 3 color fields and some 7.
Any clue?
Jacob Kaplan-Moss has an extensive writeup on dynamic form fields: http://jacobian.org/writing/dynamic-form-generation/
Essentially, you add more items to the form's self.fields
dictionary during instantiation.
这篇关于使用动态数量的字段制作 Django 表单类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!