[Fixed]-How to Insert multiple data in django to django form?

1πŸ‘

βœ…

To simplify working with related objects you can use Inline formsets

You can implement it this way:

from django.forms import inlineformset_factory
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2) 

Now in view try this:

def tambah_siswa(request):
    form = datasiswa(request.POST or None)
    FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2, fields=('SekolahID','SiswaID_FK','SekolahNama','SekolahThMasuk','SekolahThKeluar','SekolahKet'))
    if request.method == 'POST':
        if form.is_valid():
            siswa_instance = form.save()
            form2 = FormSet2(request.POST or None, instance=siswa_instance) 
            if form2.is_valid():
                form2.save()
            return redirect('index')
    form2 = FormSet2(request.POST or None) 
    formall={}
    formall['form'] = form
    formall['form2'] = form2
    return render(request, 'siswa/tambah_siswa.html', formall)

And in template:

{{ form2.management_form }}
{{ form2.as_table }}

or

{{ form2.management_form }}    
{% for frm in form2 %}
    {{ frm.as_table }}
{% endfor %}

Leave a comment