[Answered ]-Django Modelformset

1πŸ‘

βœ…

How can I now say I want to have 2 forms for example?

If you set extra parameter to 0 while creating the formset, then no extra forms will be displayed initially. To display a specific number of forms, you can pass an empty queryset to the formset’s constructor and then use the extra parameter to specify how many extra forms to display.

Use the following view to display 2 forms:

def test(request):
    AuthorFormSet = modelformset_factory(Author, form=AuthorForm, fields=('name', 'title', 'birth_date'), extra=1)
    if request.method == 'POST':
        formset = AuthorFormSet(request.POST, request.FILES)
        if formset.is_valid():
            formset.save()
            return render(request, 'voting/test.html', {'formset': formset})
    else:
        formset = AuthorFormSet(queryset=Author.objects.none())
    return render(request, 'voting/test.html', {'formset': formset})

In the template, the formset will be displayed using {{ formset }}, which will display the two forms.

Leave a comment