How to resolve FOREIGN KEY constraint failed

I am following a tutorial on a basic concept. How to customize a user in django. I don't want to use the built in auth user. I found this tutorial which seems to work until a point.

I get through the whole tutorial with everything working. however when I run my project, log in and open the user in the admin area I click "Save and continue editing" This gives me the error

The code I have in my project is EXACTLY the same as in the tutorial. I have tried removing my cache and migrations and starting again, even creating a new environment and reinstalling django. Nothing seems to work.

Environment:


Request Method: POST
Request URL: http://localhost:8000/admin/accounts/user/1/change/

Django Version: 2.0.1
Python Version: 3.5.2
Installed Applications:
['django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'accounts']
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 "/home/tate/virtenvs/tukaha-website/lib/python3.5/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 "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
  35.             response = get_response(request)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  128.                 response = self.process_exception_by_middleware(e, request)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
  126.                 response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/options.py" in wrapper
  574.                 return self.admin_site.admin_view(view)(*args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  142.                     response = view_func(request, *args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  44.         response = view_func(request, *args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/sites.py" in inner
  223.             return view(request, *args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/options.py" in change_view
  1556.         return self.changeform_view(request, object_id, form_url, extra_context)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
  62.             return bound_func(*args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapped_view
  142.                     response = view_func(request, *args, **kwargs)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
  58.                 return func.__get__(self, type(self))(*args2, **kwargs2)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/contrib/admin/options.py" in changeform_view
  1450.             return self._changeform_view(request, object_id, form_url, extra_context)

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/transaction.py" in __exit__
  212.                         connection.commit()

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in commit
  261.         self._commit()

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit
  239.                 return self.connection.commit()

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/utils.py" in __exit__
  89.                 raise dj_exc_value.with_traceback(traceback) from exc_value

File "/home/tate/virtenvs/tukaha-website/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit
  239.                 return self.connection.commit()

Exception Type: IntegrityError at /admin/accounts/user/1/change/
Exception Value: FOREIGN KEY constraint failed

I'm not sure what's going on here is this something to do with my version of django? I am using 2.0.

I have looked at similar examples on stackoverflow like this However I am not using a foreign key in the tutorial and I don't even know where the User object is being imported from on their example... Is there something I have missed or something that the tutorial has missed and I am just falling over a version issue?

To reproduce error follow the text tutorial exactly here: Then log in using your super user account. Edit the user and click save and continue editing.

Any help is appreciated


Solution 1:

I think i have found a solution for this. The problem could well be caused by the circular dependencies issues when you migrate your default AUTH_USER_MODEL to a custom model in the middle of the project.

From Django Documentation

Changing AUTH_USER_MODEL after you’ve created database tables is significantly more difficult since it affects foreign keys and many-to-many relationships, for example.

This change can’t be done automatically and requires manually fixing your schema, moving your data from the old user table, and possibly manually reapplying some migrations. See #25313 for an outline of the steps.

Due to limitations of Django’s dynamic dependency feature for swappable models, the model referenced by AUTH_USER_MODEL must be created in the first migration of its app (usually called 0001_initial); otherwise, you’ll have dependency issues.

In addition, you may run into a CircularDependencyError when running your migrations as Django won’t be able to automatically break the dependency loop due to the dynamic dependency. If you see this error, you should break the loop by moving the models depended on by your user model into a second migration. (You can try making two normal models that have a ForeignKey to each other and seeing how makemigrations resolves that circular dependency if you want to see how it’s usually done.)

The best way to tackle this is to drop the table and remove all migration files and then re run the migrations with your newly made custom model. Hope this will work.

More details on how to migrate from a built in model to a new model can be found here https://code.djangoproject.com/ticket/25313