Home > Software design >  how can I fix a 'IntegrityError at /admin/orders/order/add/' when FOREIGN KEY constraint f
how can I fix a 'IntegrityError at /admin/orders/order/add/' when FOREIGN KEY constraint f

Time:05-08

I created the order model for Django rest API, and when I tried to add an order I got an error: django.db.utils.IntegrityError: FOREIGN KEY constraint failed

That's the content of models.py :

 from django.contrib.auth import get_user_model

 User= get_user_model()
 class Order(models.Model):
     SIZES= (('SMALL','small'), ('MEDIUM','medium'), ('LARGE','large'))
     ORDER_STATUS= (('PENDING','pending'),('IN TRANSIT','in transit'),('DELIVERED','delivered'))
     customer= models.ForeignKey(User, on_delete = models.CASCADE, null = True, db_constraint=False)
     size= models.CharField(max_length=20, choices=SIZES, default=SIZES[0][0])
    order_status= models.CharField(max_length=20, choices=ORDER_STATUS, default=ORDER_STATUS[0][0])
    quantity=models.IntegerField(default=1)
    created_at=models.DateTimeField(auto_now_add=True)
    updated_at=models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"<Order {self.size} by {self.customer.id}"

and admin.py :

from django.contrib import admin
from .models import Order

@admin.register(Order)
#admin.site.register(Order)

class OrderAdmin(admin.ModelAdmin):
    list_display=['size','order_status','quantity','created_at']

how can I fix it ??

CodePudding user response:

In your models.py

from django.contrib.auth.models import User

class Order(models.Model):
   user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, db_constraint=False
...

You are getting the error because you don't have a predefined User model and you're calling get_user_model()

CodePudding user response:

@Nnaobi I already created User class in seperate application that I named authentication and that's the code of its models.py :

from django.contrib.auth.models import AbstractUser
from django.contrib.auth.base_user import BaseUserManager
from django.utils.translation import gettext_lazy as _
from phonenumber_field.modelfields import PhoneNumberField

class CustomUserManager(BaseUserManager):
   
   def create_user(self, email, password, **extra_fields):
       if not email:
           raise ValueError(_("An Email should be provided"))
       
       email= self.normalize_email(email)
       new_user= self.model(email=email, **extra_fields)
       new_user.set_password(password)
       new_user.save()
       return new_user
   def create_superuser():
       extra_fields.setdefault('is_staff',True)
       extra_fields.setdefault('is_superuser',True)
       extra_fields.setdefault('is_active',True)
       if extra_fields.get('is_staff') is not True:
           raise ValueError(_("Superuser should have is_staff as True "))
       if extra_fields.get('is_superuser') is not True:
           raise ValueError(_("Superuser should have is_superuser as True"))
       if extra_fields.get('is_active') is not True:
           raise ValueError(_("Superuser should have is_active as True"))


class User(AbstractUser):
   username=models.CharField(max_length=25, unique=True)
   email=models.EmailField(max_length=80, unique=True)
   phone_number=PhoneNumberField(null=False, unique=True)
   USERNAME_FIELD='email'
   REQUIRED_FIELDS=['username', 'phone_number']
   objects= CustomUserManager()

   def __str__(self):
       return f"<user {self.email}" ```

CodePudding user response:

@SyedMuhammadDawoudSheraz , yes the indentation errors are related to copy-paste. However, that's the traceback:

Traceback (most recent call last):
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit
    return self.connection.commit()
sqlite3.IntegrityError: FOREIGN KEY constraint failed

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\contrib\admin\options.py", line 683, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\views\decorators\cache.py", line 62, in _wrapped_view_func
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\contrib\admin\sites.py", line 242, in inner
    return view(request, *args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\contrib\admin\options.py", line 1885, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\utils\decorators.py", line 46, in _wrapper
    return bound_method(*args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\utils\decorators.py", line 133, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\contrib\admin\options.py", line 1745, in changeform_view
    return self._changeform_view(request, object_id, form_url, extra_context)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\transaction.py", line 255, in __exit__
    connection.commit()
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\backends\base\base.py", line 291, in commit
    self._commit()
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit
    return self.connection.commit()
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Mylaptop\Desktop\pizza_delivery\my_venv\lib\site-packages\django\db\backends\base\base.py", line 267, in _commit
    return self.connection.commit()
django.db.utils.IntegrityError: FOREIGN KEY constraint failed
  • Related