Initial in BaseModelFormSet

Hello,

When passing initials into a model formset, INITIAL_FORMS starts with zero, different the default formset
(I don’t have any instances of the model).

Example:

Model FormSet

class Animal(models.Model):
    name = models.CharField(max_length=5)

FormSet = modelformset_factory(Animal, fields=['name'], extra=0)
f = FormSet(initial=[{'name': 'cat'}])

print(f.management_form.initial)
# {'TOTAL_FORMS': 0, 'INITIAL_FORMS': 0, 'MIN_NUM_FORMS': 0, 'MAX_NUM_FORMS': 1000}

FormSet

class AnimalForm(forms.Form):
    name = forms.CharField()

FormSet = formset_factory(AnimalForm, extra=0)
f = FormSet(initial=[{'name': 'cat'}])

print(f.management_form.initial)
# {'TOTAL_FORMS': 1, 'INITIAL_FORMS': 1, 'MIN_NUM_FORMS': 0, 'MAX_NUM_FORMS': 1000}

I verified in the code that initial_form_count returns the value of len(self.get_queryset()) and not of the informed initials count here, is this correct?

See the ModelFormset docs on Changing the queryset and Providing initial values.

1 Like

For curiosity, do you know why it is this way and not the sum of the queryset + initial?

It is the sum of queryset + initial. See the referenced docs.