[Django]-Lazy reference: doesn't provide model user?

25👍

This:

This is caused by your settings.AUTH_USER_MODEL having changed to a model that does not exist when migrations are being computed.

… mentioned by @AKX in their answer below gave me an idea which worked.

I did the following:

  1. Do everything to put your custom User model into place. Set AUTH_USER_MODEL in settings.py and update any uses of django.contrib.auth.models.User with your custom user model.
  2. Run python manage.py makemigrations
  3. Undo step 1
  4. Run python manage.py migrate
  5. Redo step 1

10👍

For me helped split on two migration

  1. create new table (without connection between new and old tables and without AUTH_USER_MODEL = 'accounts.User')
  2. add AUTH_USER_MODEL to settings.py and other connections with new table

But it works for dev/production databases if you want to apply migrations from first in tests or another from scratch database creations you should “compact your migrations”, for me it was next steps:

  1. Make a dump of a database (in my case by sqldump)
  2. Cleanup database (especially table django_migrations)
  3. Remove all migrations in your project
  4. Run manage.py makemigrations
  5. Add migration that adds all data inserts from your old migrations
  6. Run manage.py migrate
  7. Remove table django_migrations in your dump (maybe some other django_* tables )
  8. Restore your database from a dump

9👍

This is caused by your settings.AUTH_USER_MODEL having changed to a model that does not exist when migrations are being computed.

A slightly hacky way to fix this without data loss, if you’re migrating from auth.User to custom.User is to add a “virtual” (separate database and state) minimal model (that is, only the ID field, to allow for foreign keys) according to the new User model in the very initial migration, so future migrations have this reference:

operations=[
    migrations.SeparateDatabaseAndState(
        state_operations=[
            migrations.CreateModel(
                name="User",
                fields=[
                    (
                        "id",
                        models.AutoField(
                            auto_created=True,
                            primary_key=True,
                            serialize=False,
                            verbose_name="ID",
                        ),
                    )
                ],
                options={"db_table": "auth_user"},
                managers=[("objects", UserManager())],
            )
        ]
    ),
    # ... other migrations

4👍

Warning: It will delete your whole database. If you have some important data then backup it by dumpdata and then restore it by loaddata. for more info check here (I am not sure about this).

It is very difficult to change AUTH_USER_MODEL in the middle of the project. See the note in the docs.
Infect after you are done with your first migration of Django tables, you will face problems.

Idea is: You need to include your custom user model with its entry in setting.py (AUTH_USER_MODEL = [custom user model] ) in your first-ever migration (where django create its own table like auth_group, dajango_migrations etc… ) of Django project.

Warning: If you have started server then Django itself create database and then this will not work, so please do not start the server.

  • Delete dbsqlite3 database file, delete all your migrations files and its binary files (In app/migration/pycache ) except init file and comment out all your models and it’s dependencies (like, you have used model in any form then comment it also).
  • Now uncomment only custom user model
  • add AUTH_USER_MODEL in setting.py (AUTH_USER_MODEL = [custom user model] )
  • and then run makemigrations and migrate. (this will create your all Django tables and your custom user model.)

It is done.

now you can start the server.

after that uncomment all other models and migrate them.

3👍

Alternatively, you can also try:

  1. Do python manage.py migrate <app_name> on the app that contains the custom user model.
  2. Do python manage.py migrate to apply the rest of the migrations of the app.

The reason why this works is that you’re applying the changes of the new User model first before you applied the rest of the auth model that’s built in Django.

not sure if I explained that right

2👍

WARNING: It will destroy Your current User/Group/Auth tables and entries connected with User model

Actually in django 1.9+ this is enough:

  • drop all auth_* and django_admin_log tables using the following statement :

DROP TABLE django_admin_log, auth_group, auth_group_permissions, auth_permission, auth_user, auth_user_groups, auth_user_user_permissions CASCADE;

  • delete all migrations connected with django_admin and auth apps with:

DELETE FROM django_migrations WHERE app='admin' or app='auth';

  • Then simply run:

./manage.py migrate

1👍

Easy, import to your models.py:

from django.conf import settings

then:

class SampleModel(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)

0👍

follow the below instructions

  1. create database buckup:
    pg_dump -U user_name -d database_name –data-only > file_name.sql
  2. go to .sql file path and rename using run the command:
    sed -i ‘s/auth_user/custom_user/g’ file_name.sql
  3. go to sql terminal run command:
    =# select ‘drop table if exists "’ || tablename || ‘" cascade;’ from
    pg_tables where schemaname = ‘public’;
    =#\gexec
  4. find . -path "/migrations/.py" -not -name "init.py" -delete
  5. find . -path "/migrations/.pyc" -delete
  6. python manage.py makemigrations
  7. python manage.py migrate
  8. load the .sql file to data base using this command:
    psql -U user_name -d database_name -f file_name.sql

0👍

This answer works pretty good https://stackoverflow.com/a/53460421/13542023. I migrated from custom model from 3rd party library to my model and had a problem with renaming it and this helped me a lot. Also, I found interesting workaround to make running migrations from scratch possible. I make state model proxy to old one so ForeignKey and other relations work with old model during migration process.

P.S. can’t put this under answer because of small reputation.

    operations = [
        migrations.CreateModel(
            name='OldCustomUser',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ],
            options={
                'db_table': 'relation_to_old_db',
            },
            managers=[
                ('objects', django.contrib.auth.models.UserManager()),
            ],
        ),
        migrations.SeparateDatabaseAndState(
            state_operations=[
                migrations.CreateModel(
                    name="User",
                    fields=[],
                    options={
                        'proxy': True,
                    },
                    bases=('users.OldCustomUser',),
                    managers=[("objects", django.contrib.auth.models.UserManager())],
                )
            ],
        ),
    ]

0👍

I had a similar error but i had to dump my data in json the delete the sqlite and the migrations

on Linux

 python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json

on windows

python -Xutf8 manage.py dumpdata -o data.json

Then delete the migrations and the sqlite actually i like moving my db to somewhere else just because of safe purpose but you can delete it

After deleting then run

python manage.py makemigrations
python manage.py migrate

now you load the data but please some times the below command returns an error
‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte
so to fix it just open data.json in notepad and save as then you will see save as type choose utf-8

python manage.py loaddata data.json

After this also if you notices issues you can fix it by just editting the json its readable but sure no error

0👍

I had this issue myself and this is what I did to solve:

The error:

"ValueError: The field admin.LogEntry.user was declared with a lazy
reference to ‘core_web.customuser’, but app ‘core_web’ doesn’t provide
model ‘customuser’."

The solution:

Make sure you have correctly updated the AUTH_USER_MODEL setting in your project’s settings.py file to point to the custom user model:

AUTH_USER_MODEL = 'core_web.CustomUser'

Delete all the migration files for the app core_web, except for the init.py file, located in the core_web/migrations directory.

Run the following command to create a new set of migration files for the app core_web:

python manage.py makemigrations core_web

Apply the migrations to update the database schema:

python manage.py migrate core_web

This is what fixed it for me.

-1👍

Apparently nothing was incorrect with the code, i just had to drop all my user tables and run makemigration and migrate.

-1👍

user=models.OneToOneField(User,on_delete=models.PROTECT)

-3👍

Remove all the migrations under Migration Directory

Now you can use makemigrations and migrate

Leave a comment