Ошибка Django при сохранении в базу данных : IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id

У меня есть две модели с отношением OneToMany между ними. personelModel и arizaModel. Когда я нажимаю кнопку сохранения, я получаю следующую ошибку:

"IntegrityError at / NOT NULL constraint failed: kullanici_arizamodel.p_id_id"

".

personelModel сохранена, но arizaModel не сохранена в таблице базы данных. Я хочу, чтобы обе модели были сохранены в базе данных Прошу помощи.

/my english is not good i am sorry about that/

models.py:
from email.policy import default
from tabnanny import verbose
from django.db import models

# Create your models here.
class personelModel(models.Model):
    p_sicil = models.CharField(max_length=8, verbose_name='Personel Sicili')
    p_isim = models.CharField(max_length=50, verbose_name='Personel Adı')
    p_bilgisayar_adi = models.CharField(max_length=4, verbose_name='Bilgisayar Adı')
    p_durum = models.BooleanField(default=True, verbose_name='Personel Durumu')
    
    class Meta:
        verbose_name = "Personel"
        verbose_name_plural = "Personeller"
    
    def __str__(self):
        return self.p_sicil

class arizaModel(models.Model):
    p_id = models.ForeignKey(personelModel, on_delete=models.CASCADE)
    a_aciklama = models.CharField(max_length=100, verbose_name='Arıza Açıklama')
    a_acilma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Açılma Tarihi')
    a_durum = models.BooleanField(default=True, verbose_name='Arıza Durumu')
    a_kapanma_tarihi = models.DateTimeField(auto_now_add=True, verbose_name='Kapanma Tarihi')
    
    class Meta:
        verbose_name = "Arıza"
        verbose_name_plural = "Arızalar"
        
    def __str__(self):
        return self.a_aciklama
views.py
from django.shortcuts import render
from django.urls import reverse_lazy
from kullanici.forms import PersonelBilgileriForm, ArizaBilgileriForm
    
def kullaniciArizaKaydetView(request):
    form1 = PersonelBilgileriForm(request.POST, prefix='personel_bilgileri')
    form2 = ArizaBilgileriForm(request.POST, prefix='ariza_bilgileri')
    
    if request.method == 'POST':
        if form1.is_valid() and form2.is_valid():
            personel_bilgileri = form1.save()
            ariza_bilgileri = form2.save()
                  
    return render(request, 'kullanici.html',{'PersonelBilgileriForm': form1, 'ArizaBilgileriForm': form2})
forms.py
from django import forms
from . models import personelModel, arizaModel

class PersonelBilgileriForm(forms.ModelForm):
    p_sicil = forms.CharField(widget=forms.TextInput(attrs={
        'class' : 'form-control',
        'placeholder' : 'ab sicil',
        'maxlength' : '8'
    }))
    
    p_isim = forms.CharField(widget=forms.TextInput(attrs={
        'class' : 'form-control',
        'placeholder' : 'Adınız Soyadınız',
        'maxlength' : '50'
    }))
    
    p_bilgisayar_adi = forms.CharField(widget=forms.TextInput(attrs={
        'class' : 'form-control',
        'placeholder' : 'Bilgisayar adınızın son 4 hanesi',
        'maxlength' : '4'
    }))
    
    class Meta:
        model = personelModel
        fields = ['p_sicil','p_isim','p_bilgisayar_adi']
        
class ArizaBilgileriForm(forms.ModelForm):
    a_aciklama = forms.CharField(widget=forms.Textarea(attrs={
        'class' : 'form-control',
        'placeholder' : 'Arızayı yazınız'
    }))
    class Meta:
        model = arizaModel
        fields = ['a_aciklama']
kullanici.html
<!DOCTYPE html>
<html lang="tr">

<head>
  <meta charset="UTF-8">
  <meta name="author" content="esli">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1">
  <title>Arıza Kayıt Giriş Ekranı</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.0.13/css/all.css">
</head>

<body class="bg-dark">
  <div class="container-fluid">
    <div class="row justify-content-center">
      <div class="col-md-4 mt-5 bg-light rounded">
        <h3 class="text-center fw-bold pt-3">ARIZA BİLDİRİM MERKEZİ</h3>
        <p class="text-center lead">
            Karşılaştığınız sorunu detaylı olarak açıklayınız
        </p>
        <hr class="bg-light">
        
        {% if messages %}
          {% for m in messages %}
            <div class="border bg-success text-white">
              <h5 class="text-center pt-2">{{m}}</h5>
            </div>
          {% endfor %}
        {% endif %}       
        <form action="" method="POST" id="form-box" class="p-2">
          {% csrf_token %}

          <div class="form-group input-group">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="fa fa-user"></i></span>
            </div>
            {{PersonelBilgileriForm.p_sicil}}
          </div>

          <div class="form-group input-group">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="fa fa-user"></i></span>
            </div>
            {{PersonelBilgileriForm.p_isim}}
          </div>

          <div class="form-group input-group">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="fa fa-desktop"></i></span>
            </div>
            {{PersonelBilgileriForm.p_bilgisayar_adi}}
          </div>

          <div class="form-group input-group">
            <div class="input-group-prepend">
              <span class="input-group-text"><i class="fas fa-comment-alt"></i></span>
            </div>
            {{ArizaBilgileriForm.a_aciklama}}
          </div>
          <div class="form-group">
            <input type="submit" name="submit" id="submit" class="btn btn-primary btn-block" value="GÖNDER">
          </div>
        </form>
      </div>
    </div>
  </div>
</body>

</html>

Я ожидал, что он зарегистрируется в таблице базы данных в своих данных из обеих моделей, но этого не произошло

p_id = models.ForeignKey(personelModel, on_delete=models.CASCADE)

# p_id is null when save form you must be pass personelModel instance at saving time of

form2 = ArizaBilgileriForm(request.POST, prefix='ariza_bilgileri')

-------- Подсказка ------

if request.method == 'POST':
    if form1.is_valid() and form2.is_valid():
        personel_bilgileri = form1.save()
        ariza_bilgileri = form2.save(commit=False)
        ariza_bilgileri.p_id  == personelModel.objects.get(id=1) # foreign key instance must be pass
        ariza_bilgileri.save() # then after save form 

NOTE:- в вашем случае (ariza_bilgileri = form2.save()) не получено значение p_id, поэтому выбрасывается ошибка

Вернуться на верх