I have a Django resume builder project and there is a Certificates section. Whereby, a user can enter their certificates in a form set. However, my form set is not working, I’m executing it with Javascript. When a form is entered, it seems that only the first form entry is saved, but the rest are not saved. What changes should i make so that all forms can be saved?
These are the code snippets:
forms.py:
class CertificatesForm(forms.ModelForm):
class Meta:
model = certificates
fields = [‘certificate’, ‘issuer’, ‘issuedate’, ‘description’]
labels = {
‘certificate’: ‘Certificate’,
‘issuer’: ‘Issuer’,
‘issuedate’: ‘Issuer Date’,
‘description’: ‘Description’,
}
CertificatesFormSet = formset_factory(CertificatesForm)
views.py:
@login_required
def certificate_v(request):
if request.method == ‘POST’:
formset = CertificatesFormSet(request.POST, prefix=‘certificates’)
if formset.is_valid():
for form in formset:
form.save()
return redirect(‘preview’)
else:
formset = CertificatesFormSet(prefix=‘certificates’)return render(request, 'certificates.html', {'formset': formset})
certificates.html:
{% extends “base.html” %}
{% csrf_token %} {{ formset.management_form }}
{% block content %}<div id="form-container"> {% for form in formset %} <div class="certificate-form"> {{ form.as_table }} </div> {% endfor %} </div> <button type="button" id="add-certificate-btn">Add Certificate</button> <button type="submit">Submit</button>
{% endblock %}
javascript associated:
document.addEventListener('DOMContentLoaded', function () { const formContainer = document.getElementById('form-container'); const addCertificateBtn = document.getElementById('add-certificate-btn'); addCertificateBtn.addEventListener('click', function () { const formIndex = formContainer.childElementCount; const formPrefix = `certificates-${formIndex}`; const newForm = document.createElement('div'); newForm.className = 'certificate-form'; newForm.innerHTML = document.getElementById('empty-form-template').innerHTML.replace(/__prefix__/g, formPrefix); const deleteBtn = document.createElement('button'); deleteBtn.type = 'button'; deleteBtn.innerText = 'Delete Certificate'; deleteBtn.addEventListener('click', function () { newForm.remove(); }); newForm.appendChild(deleteBtn); formContainer.appendChild(newForm); }); });
type=“text/template” id=“empty-form-template”>
{{ formset.empty_form.as_table }}