如何将可变数量的ModelForms添加到模板中?

2024-10-01 05:05:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个页面,在这里我可以创建用户想要的任意多的对象

为简单起见,有一个简单的模型:

class Person(models.Model):
    name = models.CharField(max_length=40)
    surname = models.CharField(max_length=40)

有一种形式:

class PersonCreationForm(forms.Form):
    class Meta:
        model = Person
        fields = '__all__'

现在我想要的是允许用户创建尽可能多的“人”。所以一开始,它们只能看到一个或两个PersonCreationForm,但它们可以自己添加另一个窗体

事实上,在我的例子中,它可能是有限的(假设最多20个表单)

类似于底部的“+”:

Here you can see something similar

我已经试过了:

{% for i in "xxxx" %} # tried to create 4 forms...
     {{ person_creation_form | crispy }}
{% endfor %}

我已经阅读了关于FormSets的文档,但是没有帮助

模板集:

视图.py:

from django.forms import formset_factory
PersonCreationFormSet = formset_factory(PersonCreationForm,extra=2,max_num=1)

def PersonCreationView(request):
    formset = PersonCreationFormset()
    return render(request,'person-creation.html',context={'formset':formset}

person-creation.html:

        {{ formset }} # Tried both ways (commented too)
{#            {% for x in formset %}#}
{#                {{ x | crispy }}#}
{#            {% endfor %}#}

不知道什么是较低的(额外或最大值),较低的数字是html中表单的数量,我不能调用新表单)


Tags: 用户表单formodelshtmlformslengthmax