IntegrityError when editing from admin dashboard in a new project

Summary

I am new to Django 5 and am trying to take advantage of the class-based models available. I just created an app and wanted to have a custom user model. After I created a superuser, I tired to edit a field in the superuser in admin, and on saving I get the error FOREIGN KEY constraint failed.

Tried so far

I used

python manage.py flush

to clear out the database. I then made migrations again, migrated them, and created a superuser once more. The same error happened.

Next I went into the shell and cleared the database that way

python manage.py shell
from peeps.models import CustomUser
CustomUser.objects.all().delete()
exit()

Recreating a superuser and trying to change any field in admin, returned me to the same error.

Customized Files

settings.py

AUTH_USER_MODEL = "peeps.CustomUser"

models.py

from django.contrib.auth.models import AbstractUser
from django.db import models

# Create your models here.
class CustomUser(AbstractUser):
    age = models.PositiveIntegerField(null=True, blank=True)

admin.py

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .forms import CustomUserCreationForm, CustomUserChangeForm
from .models import CustomUser

# Register your models here.
class CustomUserAdmin(UserAdmin):
    add_form = CustomUserCreationForm
    form = CustomUserChangeForm
    model = CustomUser
    list_display = [
        "email",
        "username",
        "age",
        "is_staff",
    ]
    fieldsets = UserAdmin.fieldsets + (
        (None, {
            "fields": (
                "age",
            ),
        }),
    )
    add_fieldsets = UserAdmin.add_fieldsets + (
        (None, {
            "fields": (
                "age",
            ),
        }),
    )

admin.site.register(CustomUser, CustomUserAdmin)

Error Details

Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/peeps/customuser/2/change/

Django Version: 5.1.1
Python Version: 3.12.6
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'games',
 'news',
 'reviews',
 'comm',
 'peeps']
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',
 'whitenoise.middleware.WhiteNoiseMiddleware']



Traceback (most recent call last):
  File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 303, in _commit
    return self.connection.commit()
           ^^^^^^^^^^^^^^^^^^^^^^^^

The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
  File "/usr/local/lib/python3.12/site-packages/django/core/handlers/exception.py", line 55, in inner
    response = get_response(request)
               ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/core/handlers/base.py", line 197, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/contrib/admin/options.py", line 718, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/views/decorators/cache.py", line 80, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/contrib/admin/sites.py", line 241, in inner
    return view(request, *args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/contrib/admin/options.py", line 1964, in change_view
    return self.changeform_view(request, object_id, form_url, extra_context)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/decorators.py", line 48, in _wrapper
    return bound_method(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/decorators.py", line 188, in _view_wrapper
    result = _process_exception(request, e)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/decorators.py", line 186, in _view_wrapper
    response = view_func(request, *args, **kwargs)
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/contrib/admin/options.py", line 1819, in changeform_view
    with transaction.atomic(using=router.db_for_write(self.model)):
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/transaction.py", line 263, in __exit__
    connection.commit()
    ^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/utils/asyncio.py", line 26, in inner
    return func(*args, **kwargs)
           ^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 327, in commit
    self._commit()
    ^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 302, in _commit
    with debug_transaction(self, "COMMIT"), self.wrap_database_errors:
                                            ^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/utils.py", line 91, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/site-packages/django/db/backends/base/base.py", line 303, in _commit
    return self.connection.commit()
           ^^^^^^^^^^^^^^^^^^^^^^^^

Exception Type: IntegrityError at /admin/peeps/customuser/2/change/
Exception Value: FOREIGN KEY constraint failed

Again, this is a brand new project. There are no other models in the database besides the superuser. What am I overlooking to cause this error?

Welcome @makisegfault !

Did you create your custom user model before or after running your initial migration?
If you ran your initial migration first (before creating your user model), then the easiest thing to do is to drop your database and recreate it.

The basic issue in this specific situation is that the admin log tables aren’t created correctly.

For a more detailed explanation on this, see the Substituting a custom User model docs, particularly the section on Changing to a custom user model mid-project.

Hello!

Yes, I created the superuser after the initial migration. After following the links you posted, I found my answer is this ticket thread.

Since my project was brand new, the database had nothing in it that I needed to save. So first I flushed all the migrations like before

python manage.py flush

And then I deleted the database file.

Next, I added this to my custom user model class

    class Meta:
        db_table = 'auth_user'

Finally, I made the migrations, migrated them, and created a superuser.

It works perfectly fine now and I can edit fields in the admin.

Thank you for your help!

This is a belated response, but I am leaving this message because it is possible to solve the problem in other ways.

The problem occurred because the django_admin_log table references the auth_user table.

  1. Keep migrations up to date.
  2. Delete the django_admin_log table.
  3. run python manage.py migrate --fake admin zero, run python manage.py migrate --fake-initial

Previous records made on the administrator page will be removed, but you can use the Django project without any problems afterward.

The following link is an article I wrote to remember.(written in Korean)