Django generates wrong number of forms in formset after initialization

Viewed 193

I have following declaration of Formset:

ModelAFormSet = generic_inlineformset_factory(
    ModelA,
    form=AddModelAForm,
    formset=BaseModelAFormset,
    min_num=1,
    extra=0)

and ModelA looks as follows:

class ModelA(models.Model):
   name = models.CharField(max_length=100)
   description = models.CharField(max_length=100)

   content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
   object_id = models.PositiveIntegerField()
   model_object = GenericForeignKey('content_type', 'object_id')

When I'm initializing my formset following way:

init_list = []
for my_model in self.edit_parent.my_models.all():
   dictionary = { 
     'name': my_model.name,
     'description': my_model.description,
     'id': my_model.id}
   init_list.append(dictionary)

formset = ModelAFormSet(initial=init_list)

I am always generating only one record. No matter what the len(init_list) is. I've been trying to find explanation for this, but no luck.

Additional info After removing min_num and extra from ModelAFormSet resulting in

ModelAFormSet = generic_inlineformset_factory(
    ModelA,
    form=AddModelAForm,
    formset=BaseModelAFormset)

Number of generated forms is sort of correct. I have 2 forms which I would expect wit data assigned to them and (that's incorrect part) one extra empty form. What's more when I completely remove min_num no form is generated.

1 Answers

The extra argument should be equivalent to the number of forms you expect to see. There's no need to set min_num unless you want to validate the number of forms.

class MyView(generic.CreateView):
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        init_list = [...]
        formset = generic_inlineformset_factory(
            ...
            extra=len(init_list),
        )
        context['formset'] = formset(
            self.request.POST or None,
            initial=init_list,
        )
        return context
Related