IntegrityError at /admin/userauths/user/add/



Request Method: POST
Request URL: http://127.0.0.1:8000/admin/userauths/user/add/

Django Version: 5.0.1
Python Version: 3.12.5
Installed Applications:
['jazzmin',
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'hotel',
 'user_dashboard',
 'addon',
 'userauths',
 'import_export',
 'crispy_forms',
 'mathfilters',
 'ckeditor_uploader',
 'django_ckeditor_5',
 'taggit']
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']```
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 299, in _commit
    return self.connection.commit()
           ^^^^^^^^^^^^^^^^^^^^^^^^

The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\core\handlers\base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\options.py", line 714, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\views\decorators\cache.py", line 80, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\sites.py", line 240, in inner
    return view(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\options.py", line 1941, in add_view
    return self.changeform_view(request, None, form_url, extra_context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\decorators.py", line 48, in _wrapper
    return bound_method(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\contrib\admin\options.py", line 1801, in changeform_view
    with transaction.atomic(using=router.db_for_write(self.model)):
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\transaction.py", line 263, in __exit__
    connection.commit()
    ^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\utils\asyncio.py", line 26, in inner
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 323, in commit
    self._commit()
    ^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 298, in _commit
    with debug_transaction(self, "COMMIT"), self.wrap_database_errors:
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\Emmanuel_coder\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\base\base.py", line 299, in _commit
    return self.connection.commit()
           ^^^^^^^^^^^^^^^^^^^^^^^^

Exception Type: IntegrityError at /admin/userauths/user/add/
Exception Value: FOREIGN KEY constraint failed

What is this error message telling you?

What class or file do you think you need to inspect to find the cause of this?

my admin.py right or

That would probably be the best place to start.

However, given that this is an error related to the saving of a model, it’s possible that the error is in the model as well.

1 Like

so how can we solve this issue

The first thing would be to identify the real cause of the issue. That means we’re going to need to see the models and the model admin classes.

from django.contrib.auth.models import AbstractUser
from django.db.models.signals import post_save
from shortuuid.django_fields import ShortUUIDField

GENDER = (
    ("Female",  "Female"),
    ("Male",  "Male"),
    ("Other", "Other"),
)

IDENTITY_TYPE = (
    ("National Identification Number","National Identification Number"),
    ("Driver's License", "Driver's License"),
    ("Internationa Passport", "Internationa Passport"),
)

def user_directory_path(instance, filename):
    ext = filename.split(".")[-1]
    filename = "%s.%s" % (instance.user.id, filename)
    return "user_(0)/(1)".format(instance.user.id, filename)

class User(AbstractUser):
    full_name = models.CharField(max_length=500, null=True, blank=True)
    username = models.CharField(max_length=500, unique=True)
    email = models.EmailField(unique=True)
    phone = models.CharField(max_length=100, null=True, blank=True)
    gender = models.CharField(max_length=20, choices=GENDER, default="other")

    otp = models.CharField(max_length=100, null=True, blank=True)

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def __str__(self):
        return self.username
    
    #Himselv User

class Profile(models.Model):
        pid = ShortUUIDField(length=7, max_length=25, alphabet="abcdefghijklmnopqrstuvwxyz123")
        image = models.FileField(upload_to=user_directory_path, default="default.jpg", null=True, blank=True)
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        full_name = models.CharField(max_length=500, null=True, blank=True)
        phone = models.CharField(max_length=100, null=True, blank=True)
        gender = models.CharField(max_length=20, choices=GENDER, default="other")

        country = models.CharField(max_length=100, null=True, blank=True)
        city = models.CharField(max_length=100, null=True, blank=True)
        state = models.CharField(max_length=100, null=True, blank=True)
        address = models.CharField(max_length=1000, null=True, blank=True)

        identity_type = models.CharField(max_length=200, choices=IDENTITY_TYPE, null=True, blank=True)
        identity_image = models.FileField(upload_to=user_directory_path, default="default.jpg", null=True, blank=True)
    

        facebook = models.URLField(null=True, blank=True)
        twitter =  models.URLField(null=True, blank=True)

        wallet = models.DecimalField(max_digits=12, decimal_places=2, default=0.00)
        verified = models.BooleanField(default=False)

        date = models.DateTimeField(auto_now_add=True)

        class Meta:
            ordering = ["-date"]

        def __str__(self):
             if self.full_name:
                  return f"{self.full_name}"
             else:
                 return f"{self.user.username}"
             
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user = instance)

def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

post_save.connect(create_user_profile, sender=User)
post_save.connect(save_user_profile, sender=User)
from userauths.models import User,Profile

class UserAdmin(admin.ModelAdmin):
    search_fields = ['full_name', 'username']
    list_display = ['username', 'full_name', 'email', 'phone', 'gender']

class ProfileAdmin(admin.ModelAdmin):
    search_fields = ['full_name', 'user_username']
    list_display = ['full_name', 'user', 'verified']

admin.site.register(User, UserAdmin)
admin.site.register(Profile, ProfileAdmin)

please i need you help

I cannot recreate the issue you’re reporting here using standard Django. This implies that there’s another app involved that is causing this issue.

I would try removing apps one-by-one until you identify the problematic app.

i will i know daddy thats why i am here to get answers to my question please take your time on me and help me am jxt a boy trying my best to understand

There’s nothing else I can do at the moment to help.

I don’t see anything wrong with the code you’ve posted, and I can’t recreate the issue in a basic Django environment.

This means that you’re going to need to do some work to start narrowing down the source of the issue. You’ve got something in your project somewhere that is causing this. That means you’ll need to start narrowing down what’s going on until you’ve identified what that is.

I Clean the database this will clean all the database data including superuser

python manage.py flush

I Run the migrations

python manage.py makemigrations
python manage.py migrate

I Now create a superuser

python manage.py createsuperuser

and it works for me

1 Like

This is not an accurate statement. It cleans application-created data from the database, it does not clean django-created data. (It doesn’t clean ContentType, Migration, or Permission)

I am glad you found a solution!

1 Like