[Fixed]-How to get ID from another model in django?

1👍

You can use ForeignKey field.

class RiwayatSekolah(models.Model):
    SekolahID=models.AutoField(primary_key=True)
    SiswaID_FK=models.ForeignKey(DataPribadiSiswa)

Now in view you can try to save Siswa instance first and then to add it into Sekolah instance:

def tambah_siswa(request):
    form = datasiswa(request.POST)
    form2 = riwayatsekolah(request.POST)
    if request.method == 'POST':
        if form.is_valid() and form2.is_valid():
            siiswa_instance = form.save()
            Sekolah_instance = form2.save(commit=False)
            Sekolah_instance.SiswaID_FK = siiswa_instance
            Sekolah_instance.save()  

Leave a comment