我在Django表单中遇到了一些问题,在我看来应该已经有了解决方案。
我有几种不同的表单在同一个视图中提交,例如......(抱歉现在只使用伪代码)..
class Form1():
#different attributes
class Form2()
#different attributes
<html>
<form>
{{ 1-instance-Form1 }}
{{ 2-instance-Form1 }}
{{ 1-instance-Form2 }}
{{ 2-instance-Form2 }}
</form>
</html>
除此之外,我想让用户能够通过jquery添加其中一个表单类的表单实例,以便表单可能成为
<html>
<form>
{{ 1-instance-Form1 }}
{{ 2-instance-Form1 }}
{{ 1-instance-Form2 }}
{{ 2-instance-Form2 }}
{{ 3-instance-Form2 }}
</form>
</html>
现在在寻找处理这样一个问题的解决方案时,我遇到了Django formset的概念,正如文档描述的那样,它是同一Form类的实例的集合。但是正如我所看到的,formsets也可以处理异构表单:
改变了一些定义
class BaseHeterogenousFormSet(StrAndUnicode):
def append(form):
#add one more form to the formset
def is_valid():
#run is_valid for each of the forms in the formset
def clean():
#run the clean for each of the forms ...
我在考虑这个问题的方式有问题吗?
答案 0 :(得分:5)
您可以向同一视图提交多个formset,但您需要避免名称冲突(https://docs.djangoproject.com/en/1.6/topics/forms/formsets/#using-more-than-one-formset-in-a-view)
一个formset处理Form1的实例,另一个formset处理Form2的实例。