我想从form2向我的数据库插入多行。以下是我的代码
首先是model.py
class DataPribadiSiswa(models.Model):
SiswaID = models.AutoField(primary_key=True)
WaliKelasID=models.CharField(max_length=5,blank=True,null=True)
第二个model.py
class RiwayatSekolah(models.Model):
SekolahID=models.AutoField(primary_key=True)
SiswaID_FK=models.ForeignKey(DataPribadiSiswa,blank=True, null=True)
SekolahNama=models.CharField(max_length=50,blank=True,null=True)
SekolahThMasuk=models.CharField(max_length=4,blank=True,null=True)
SekolahThKeluar=models.CharField(max_length=4,blank=True,null=True)
SekolahKet=models.TextField(blank=True,null=True)
views.py
def tambah_siswa(request):
form = datasiswa(request.POST)
form2 = riwayatsekolah(request.POST)
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, instance=siswa_instance)
if form2.is_valid():
form2.save()
return redirect('index')
else:
formall={}
formall['form'] = datasiswa()
formall['form2'] = riwayatsekolah()
return render(request, 'siswa/tambah_siswa.html', formall)
这是我的模板
<form action="" method="post">
{% csrf_token %}
<table >
{{ form2.management_form }}
{{ form2.as_table }}
</table>
</form>
如何将form2中的多行插入数据库?当我运行此代码时,它只插入一行。
答案 0 :(得分:1)
为了简化对相关对象的处理,您可以使用Inline formsets
您可以这样实现:
from django.forms import inlineformset_factory
FormSet2 = inlineformset_factory(DataPribadiSiswa, RiwayatSekolah, extra=2)
现在查看试试这个:
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)
在模板中:
{{ form2.management_form }}
{{ form2.as_table }}
或
{{ form2.management_form }}
{% for frm in form2 %}
{{ frm.as_table }}
{% endfor %}