将 Django 表单集呈现为数组

Render Django formset as array

我有一个模型,我需要创建包含多个实例的表单。更具体地说:我需要将我的 ModelForm 渲染成常规形式,并在其字段名称旁边加上方括号。魔法世界中的类似内容:

forms.py

class ManForm(ModelForm):
    class Meta:
        model = Man
        fields = ['name', 'age']

class PeopleForm(forms.Form):
    # modelless form
    people = ??? # array of ManForm instances or something

form.html

<form action="/people/create/">
    {{ form }}
</form>

输出

<form action="/people/create/">
    <input type="text" name="name[0]"/>
    <input type="text" name="age[0]"/>
</form>

说实话,我完全不知道如何解决这个问题。我尝试了 modelformset_factory,但我得到的只是 <input type="text" name="form-0-name"/>

如评论中所述,您需要一个表单集。

def create_people(request):
    PeopleFormSet = modelformset_factory(Man, form=ManForm)
    if request.method == 'POST':
        formset = PeopleFormSet(request.POST)
        if formset.is_valid():
            for form in formset:
                ... do something with individual form
    else:
        formset = PeopleFormSet()
    return render(request, template_name, {'formset': formset}

要在基于函数的视图中使用表单集,请参阅@Daniel Roseman 的回答或阅读 here

对于基于 class 的视图,没有内置通用视图。根据this ticket they decided to let third-party-packages handle that. You can use django-extra-views的说法。