使用动态数量的字段制作Django表单类 [英] Making a Django form class with a dynamic number of fields

查看:126
本文介绍了使用动态数量的字段制作Django表单类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个像在线商店的东西。我正在做一个客户购买一个物品的表格,她可以选择她想要购买的这些物品。但是,在她购买的每个项目上,她都需要选择它的颜色。所以有一个非常多的字段:如果客户购买3个项目,她应该得到3个< select> 框选择颜色,如果她购买7个项目,她应该得到7个这样的< select> 框。



我将使HTML表单字段出现并消失使用JavaScript。但是我在Django表单类中如何处理?我看到表单域是类属性,所以我不知道如何处理一些表单实例应该有3个颜色字段和一些7。



任何线索?

解决方案

Jacob Kaplan-Moss在动态表单字段上有广泛的写作:
http://jacobian.org/writing/dynamic-form-generation/



基本上,在实例化过程中,您可以在表单的字段成员变量中添加更多项目。


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 fields member variable during instantiation.

这篇关于使用动态数量的字段制作Django表单类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆