I have a formset with 1 extra form:
IdentifierFormset = inlineformset_factory(
Mixture, Identifier, form = IdentifierForm,
extra = 1,
can_delete = True, can_delete_extra = True,
)
I use javascript to add new forms (with each new form increasing TOTAL_FORMS):
$('#add-identifier-button').click(function(ev) {
ev.preventDefault();
var count = $('#item-identifier_formset').children().length;
var tmplMarkup = $('#identifier_formset-template').html();
var compiledTmpl = tmplMarkup.replace(/__prefix__/g, count);
$('#item-identifier_formset').append(compiledTmpl);
// update forms count
$('#identifier_formset-TOTAL_FORMS').attr('value', count+1);
However when formset is invalid, only 1 form in formset is displayed. How can I keep added forms?
What does your view look like that is handling this formset?
class MixtureEditParentView():
model = Mixture
form_class = MixtureForm
template_name = 'mixture_form.html'
def form_valid(self, form):
identifier_formset = self.get_identifier_formset()
if not identifier_formset.is_valid():
return self.render_to_response(self.get_context_data(form=form))
self.object = form.save()
self.identifier_formset_valid(identifier_formset)
return redirect(self.get_success_url())
def identifier_formset_valid(self, identifier_formset):
identifiers = identifier_formset.save(commit=False)
for obj in identifier_formset.deleted_objects:
obj.delete()
for identifier in identifiers:
identifier.mixture = self.object
identifier.save()
def form_invalid(self, form):
return self.render_to_response(self.get_context_data(form=form,))
class MixtureCreateView(MixtureEditParentView, CreateView):
def get_form_kwargs(self, **kwargs):
form_kwargs = super(MixtureCreateView, self).get_form_kwargs(**kwargs)
form_kwargs["language"] = self.request.session['language']
return form_kwargs
def get_context_data(self, **kwargs):
data = super(MixtureCreateView, self).get_context_data(**kwargs)
data['identifier_formset'] = self.get_identifier_formset()
return data
def get_identifier_formset(self):
if self.request.method == 'GET':
return IdentifierFormset(prefix = 'identifier_formset', form_kwargs={'language': self.request.session['language']})
else:
return IdentifierFormset(self.request.POST or None, prefix = 'identifier_formset', form_kwargs={'language': self.request.session['language']})
def get_success_url(self) -> str:
return 'create-mixture-composition'
To clarify information from your first post - if all the forms are valid, do they all submit and save as expected? (Is the only problem occurring when there is an invalid form in the formset?)
No, only the first one Sorry, I didn’t knew.
Ok, so the next thing I can think of to check is what exactly is the html being generated in the formset for the additional forms. Please post the html from the browser after one or two additional forms have been added.
Oh, now I see! I had a typo in input ID for TOTAL_FORMS value. So it wasn’t updating the forms count. Thanks for navigating me.