djangomodel

Foreign key constraint failed


I have a complex model with optional fields, I try to save it using my form and I get an error every time: 'FOREIGN KEY constraint failed'.

My all fields in the table are optional, and the form is empty, so it should allow you to save the empty model.

models.py

class Ordering(models.Model):
    massage_product = models.OneToOneField(Product, on_delete=models.CASCADE, null=True, blank=True, default = 1)
    masseurs = models.OneToOneField(Masseurs, on_delete=models.CASCADE, null=True,  blank=True, default = 1)
    massage_time_interval = models.CharField(max_length=5, blank=True)
    price = models.CharField(max_length=5, blank=True)
    day_week = models.CharField(max_length=15, choices=DAY_OF_WEEK, default=date.today, blank=True)
    time = models.OneToOneField(Time, on_delete=models.CASCADE, null=True, blank=True, default = 1)
    place = models.OneToOneField(PlaceMassage, on_delete=models.CASCADE, null=True, blank=True, default = 1)
    payment_method = models.CharField(max_length=1, choices=PAYMENT_METHODS, default='G', blank=True)
    name = models.CharField(max_length=50, blank=True)
    surname = models.CharField(max_length=50, blank=True)
    e_mail = models.EmailField(blank=True)
    additional_requests = models.TextField(blank=True)
    phone_number = models.CharField(max_length=15, blank=True)
    reminder_visit = models.BooleanField(default=True, blank=True)
    website_rules = models.BooleanField(default=True, blank=True)
    city = models.CharField(max_length=50, blank=True)
    street = models.CharField(max_length=50, blank=True)
    street_number = models.CharField(max_length=10, blank=True)
    hom_number = models.CharField(max_length=10, blank=True)
    zip_code = models.CharField(max_length=10, blank=True)
    created_at_data = models.DateTimeField(auto_now_add=True)
    updated_at_data = models.DateTimeField(auto_now=True)

forms.py

if request.method == 'POST' and 'btn_massage_order' in request.POST:
    ordering_form = OrderingMassageForm(data=request.POST)
    if ordering_form.is_valid():
        ordering = OrderingMassage()
        ordering.save()
else:
     ordering_form = OrderingMassageForm()

Error Environment:

Request Method: POST
Request URL: http://127.0.0.1:8000/massage_order/2_1_90_100/

Django Version: 2.0
Python Version: 3.7.0
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'app',
 'multiselectfield',
 'crispy_forms']
Installed Middleware:
['django.middleware.security.SecurityMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware']



Traceback:

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py" in _commit
  239.                 return self.connection.commit()

The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner
  35.             response = get_response(request)

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:\Users\tymot\Desktop\PROJEKT\app_test_form-czysty\app_rama\app\views.py" in massage_order
  399.             ordering.save()

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save
  729.                        force_update=force_update, update_fields=update_fields)

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py" in save_base
  759.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\transaction.py" in __exit__
  212.                         connection.commit()

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py" in commit
  261.         self._commit()

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py" in _commit
  239.                 return self.connection.commit()

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "C:\Users\tymot\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py" in _commit
  239.                 return self.connection.commit()

Exception Type: IntegrityError at /massage_order/2_1_90_100/
Exception Value: FOREIGN KEY constraint failed

Django admin allows you to save an empty form, so why does not my allow it?


Solution

  • try this

    if request.method == 'POST' and 'btn_massage_order' in request.POST:
        ordering_form = OrderingMassageForm(request.POST)
        if ordering_form.is_valid():
            ordering = ordering_form(commit=False)
            ordering.save()
    else:
         ordering_form = ordering_form()
    

    hope it helps