Hi everyone,
0
I am facing a problem when adding dynamically a new form in a table with JS. The formset is generated. I can add a new line, but when I submit my formset, the last line is not detected, the error gives me :
Formset errors sont: [{}, {}, {}, {‘num’: [‘This field is required.’], ‘description’: [‘This field is required.’]}]
Do you have any clues what should be the problem?
Thanks a lot! Regards models.py
class Link1(models.Model):
num=models.IntegerField()
description=models.CharField(max_length=100)
class Case(models.Model):
link=models.ManyToManyField(Link1,related_name='cases')
forms.py
class Form1(forms.Form):
num=forms.IntegerField(label=None,widget=forms.Select(choices=liste_1,attrs={'class': 'custom-select text-white','style':'background-color:#063c5c'}))
description=forms.CharField(label=None,max_length=100, widget=forms.Select(choices=liste_description,attrs={'class': 'custom-select text-white', 'style':'background-color:#063c5c'}))
views.py
def validation2(request, case_id):
case = get_object_or_404(Case, id=case_id)
case_id2=case.id
formset1=formset_factory(Form1,extra=0)
if request.method=="POST":
myform = formset1(request.POST)
if myform.is_valid():
case.link.clear()
for f in myform:
cd=f.cleaned_data
print("cd:")
print(cd)
#On va effacer et réaffecter tout!
numero=int(cd['num'])
desc=cd['description']
obj,boleensiexiste=Link1.objects.get_or_create(num=numero,description=desc)
case.link.add(obj)
case.save()
return redirect(reverse('validation1', kwargs={'case_id': case_id2}))
else:
liste_initiales=[]
for link in case.link.all():
liste_initiales.append({'num': link.num ,'description':link.description})
myform=formset1(initial=liste_initiales)
print(myform)
context={'myform':myform, 'case':case}
return render(request,'analyzis.html', context)
html
<table id="TableRecap" class="table order-list table-borderless text-white p-0 mx-5" style="background-color:#063c5c">
<thead>
<tr>
<th scope="col" ><div class="text-center"><h5></h5></div></th>
<th scope="col" ><div class="text-center"><h5></h5></div></th>
<th scope="col"> </th>
</tr>
</thead>
<form action="{% url "validation2" case.id%}" method="post">
{% csrf_token %}
{{ myform.management_form }}
<tbody id="myTableBody">
{% for formz in myform %}
<tr><td>
{{ formz.num }}
</td><td>
{{ formz.description}}
</td><td>
<img class="btn-validate text-info" src="{% static '/check.png' %}" width="35" height="35" alt="validate"/>
<img class="btn-delete" src="{% static '/x.png' %}" width="30" height="30" alt="delete" />
</td></tr>
{% endfor %}
</tbody>
<tfoot>
<tr><td>
</td><td>
<input type="button" class="btn btn-info float-md-right" id="addrow" value="Ajouter un élément" />
</td><td>
<input type="submit" class="btn btn-info float-md-left" value="Valider"/>
</td></tr>
</tfoot>
</form>
</table>
js
```
$("body").on("click", "#addrow", function(){
var compteur=$("#id_form-TOTAL_FORMS").attr("value");
alert(compteur);
var num = '<td><select name="form-'+ compteur +'-num" class="form-control text-white text-center" style="background-color:#143244" id="id_form-'+ compteur +'-num"><option value="11" >11</option><option value="12" selected>12</option></select></td>';
var des = '<td><select name="form-'+ compteur +'-description" class="form-control text-white" style="background-color:#143244" maxlength="100" id="id_form-'+ compteur +'-description"><option value="d">d</option><option value="c" selected>c</option><option value="ab">ab</option></select></td>';
var ligne = '<tr class="valide">' + num + des ;
ligne += '<td>'+'<img type="button" src='+ url1 +' width="35" height="35" class="btn-validate" alt="validate" onclick="validate()" />'
ligne +='<img type="button" class="btn-delete" src='+ url3 +' width="30" height="30" alt="delete" />'+'</td></tr>';
/* alert(ligne); */
compteur++;
$("#myTableBody").append(ligne);
$("#id_form-TOTAL_FORMS").attr("value",compteur);
$("#id_form-INITIAL_FORMS").attr("value",compteur);
alert($("#id_form-TOTAL_FORMS").attr("value"));
});
$("body").on("click", ".btn-delete", function(){
var compteur=$("#id_form-TOTAL_FORMS").attr("value");
var indice=$(this).parents("tr").index();
$(this).parents("tr").remove();
compteur -= 1;
depart = indice-1;
$('#myTableBody tr:gt('+depart+')').each(function(){
a=$(this).find("td:eq(0) select").attr("id");
$(this).find("td:eq(0) select").attr("id",'id_form-'+ indice +'-num');
$(this).find("td:eq(0) select").attr("name",'form-'+ indice +'-num');
$(this).find("td:eq(1) select").attr("id",'id_form-'+ indice +'-description');
$(this).find("td:eq(1) select").attr("name",'form-'+ indice +'-description');
b=$(this).find("td:eq(0) select").attr("id");
indice++;
});
$("#id_form-TOTAL_FORMS").attr("value", compteur);
```