Django.db.utils.IntegrityError: FOREIGN KEY Constraint Failed
Solution 1:
The error is in the line:
order = Order.objects.create(user=user, customer_name=name, customer_phone=phone, status_id=1)
You have to pass a status instance for the field
I stand corrected, it can work; see this post.status
because it is a ForeignKey
field. Just setting status_id
to an integer won't work.
Your error probably happens because either user
(or user_id
) or status
(or status_id
) are referencing instances that don't exist in the related database table.
Are you sure that there is a status with pk=1
? Does the operation Status.objects.get(pk=1)
succeed?
Solution 2:
Try setting the named parameter of db_constraint
of models.ForeignKey()
to False
(by default its True
) like this:
status = models.ForeignKey(Status, on_delete=models.PROTECT,db_constraint=False)
This worked for me on a certain project the only issue will be that you will be unable to ensure the integrity of your db (e.g knowing whether all the Status objects referenced actually exist) but it makes sense if you're working with legacy code. Hope it helps.
Solution 3:
I see you didn't save the instance "order". ---- order.save()
I think the solution is to save instaces to be saved.
Today, I had the same error message as you did. I realized that I forgot to save an instance in my code. My code is different from your code, but I think you're worth trying
Solution 4:
I had this problem, because I used the wrong form.
Check your code for the form. I don't see where do you use it after if form.is_valid():
check.
Post a Comment for "Django.db.utils.IntegrityError: FOREIGN KEY Constraint Failed"