Nets
Nets

Reputation: 141

Multiple model formsets in Django

I have a modelformset AddressFormSet = modelformset_factory(Address). In my view I assign this formset to different context variables, but they seem to be duplicated. The input names are the same.

def get_context_data(self, **kwargs):
    context = super(TravelCreate, self).get_context_data(**kwargs)
    if self.request.POST:
        context['address1'] = AddressFormSet(self.request.POST)
        context['address2'] = AddressFormSet(self.request.POST)
    else:
        context['address1'] = AddressFormSet(queryset=self.model.objects.none())
        context['address2'] = AddressFormSet(queryset=self.model.objects.none())
    return context

How can I give them different names so data from both formsets creates objects.

Upvotes: 1

Views: 303

Answers (1)

Thomas
Thomas

Reputation: 11888

You need to provide both Formsets with a different prefix when you create them from a factory, otherwise they will both be working with the same names from the post data

def get_context_data(self, **kwargs):
    context = super(TravelCreate, self).get_context_data(**kwargs)
    if self.request.POST:
        context['address1'] = AddressFormSet(self.request.POST, prefix='address1')
        context['address2'] = AddressFormSet(self.request.POST, prefix='address2')
    else:
        context['address1'] = AddressFormSet(queryset=self.model.objects.none(), prefix='address1')
        context['address2'] = AddressFormSet(queryset=self.model.objects.none(), prefix='address2')
    return context

REF: https://docs.djangoproject.com/en/1.5/topics/forms/formsets/#using-more-than-one-formset-in-a-view

Upvotes: 1

Related Questions