I have been trying to solve this for weeks to no avail, and would really appreciate some help.
Background
I'm creating a Django app which takes input of a user's educational experience, and wanted to provide users with the ability to add new experiences via an "Add More" button (i.e if they had an undergrad and masters).
I'm doing this using ModelFormsets and Jquery, following this answer: Dynamically adding a form to a Django formset with Ajax.
Problem When accessing the cleaned_data of the formset, only the first initial form has values in its cleaned_data, the additional generated forms return an empty dictionary with no cleaned data in them.
Views.py
EducationFormset = modelformset_factory(Education, form=EducationForm, fields=('institution', 'degree', 'major', 'major_start_date', 'major_end_date', 'major_description', 'gpa',))
if request.method == 'POST':
formset = EducationFormset(request.POST, request.Files)
if formset.is_valid():
formset.save()
for form in formset.forms:
print(form.cleaned_data)
else:
print(formset.errors)
else:
formset = EducationFormset(queryset=Education.objects.none())
context = {
'user_form': user_form,
'education_form': education_form,
'experience_form': experience_form,
'formset':formset,
}
return render(request, 'create.html', context)
HTML
{{ formset.management_form }}
<div id="form_set">
<div class="form-group">
{% for form in formset.forms %}
{{form.errors}}
<table class="no_error">
{{form.as_table}}
</table>
{% endfor %}
</div>
</div>
<div id="empty_form" style="display:none">
<table class="no_error">
{{formset.empty_form.as_table}}
</table>
</div>
<script>
$('#add_more').click(function() {
var form_idx = $('#id_form-TOTAL_FORMS').val();
$('#form_set').append($('#empty_form').html().replace(/__prefix__/g, form_idx));
$('#id_form-TOTAL_FORMS').val(parseInt(form_idx) + 1);
});
</script>
Models.py
class Education(models.Model):
institution = models.CharField(max_length = 120, blank=True)
degree = models.CharField(max_length = 120, blank=True)
major = models.CharField(max_length = 120, blank=True)
major_start_date = models.CharField(max_length = 120, blank=True)
major_end_date = models.CharField(max_length = 120, blank=True)
gpa = models.CharField(max_length = 120, blank=True)
major_description = models.CharField(max_length = 120, blank=True)