Django Form with ForeignKey field NOT NULL constraint failed Error

Each model is chain-linked to the previous model. I make one form to fill in, since all the models are linked. When I try to link a model address to a project, an error appears

NOT NULL constraint failed: crm_project.address_id /crm/views.py, line 39, in add_project form_project.save()

Models

class City(models.Model):
    obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион")
    name = models.CharField(max_length=128, verbose_name="Город")
    population = models.IntegerField()

    def __str__(self):
        return self.name


class Address(models.Model):
    city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город")
    street = models.CharField(max_length=255, verbose_name="Улица")
    numb = models.CharField(max_length=64, verbose_name="Номер дома")

    def __str__(self):
        return f"{self.street}, {self.numb}"

class Project(models.Model):
    manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник")
    address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес")
    # another fields

class ProjectDetail(models.Model):
    project = models.OneToOneField(Project, on_delete=models.CASCADE, verbose_name="Проект")
    # another fields

Forms

class AddressForm(forms.ModelForm):
    class Meta:
        model = Address
        fields = ["city", "street", "numb"]

    def __init__(self, *args, **kwargs):
        city = kwargs.pop("city", "")
        super(AddressForm, self).__init__(*args, **kwargs)
        self.fields["city"] = forms.ModelChoiceField(queryset=City.objects.all())


class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = ["file", "sq", "rent_tax"]

class ProjectDetailForm(forms.ModelForm):
    class Meta:
        model = ProjectDetail
        exclude = ['project', 'comment', 'resume', 'complite', 'created_at']

Views

def add_project(request):
    form_address = AddressForm(request.POST or None)
    form_project = ProjectForm(request.POST or None)
    form_detail = ProjectDetailForm(request.POST or None)

    if request.method == 'POST':
        if form_address.is_valid() and form_project.is_valid() and form_detail.is_valid():
            address = form_address.save(commit=False)
            form_project.manager = request.user
            form_project.address = address
            project = form_project.save(commit=False)
            form_detail.project = project

            form_address.save()
            form_project.save()
            form_detail.save()

    
    context = {'form_address':form_address, 'form_project':form_project, 'form_detail':form_detail,}

    return render(request, 'crm/project_form.html', context)

in your ProjectForm you specified these fields only fields = ["file", "sq", "rent_tax"] but as per Your Model:

class Project(models.Model):
    manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник")
    address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес")

There two fields are null=FalseMeans every instance of Project must have these Values which you're not providing in the ProjectForm

to handle this error you can do 2 things as per your need.

  1. replace this form with this:

class ProjectForm(forms.ModelForm):
    class Meta:
        model = Project
        fields = '__all__"

or another option which is not how you should use foreign keys.

  1. change your class with this and makemigrations and migrate again:
class Project(models.Model):
    manager = models.ForeignKey(User, on_delete=models.PROTECT,null=True, blank=True, verbose_name="Сотрудник")
    address = models.ForeignKey(Address, on_delete=models.PROTECT, null=True, blank=True,verbose_name="Адрес")
Back to Top