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:
- Do everything to put your custom
User
model into place. SetAUTH_USER_MODEL
insettings.py
and update any uses ofdjango.contrib.auth.models.User
with your custom user model. - Run
python manage.py makemigrations
- Undo step 1
- Run
python manage.py migrate
- Redo step 1
10
For me helped split on two migration
- create new table (without connection between new and old tables and without
AUTH_USER_MODEL = 'accounts.User'
) - add
AUTH_USER_MODEL
tosettings.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:
- Make a dump of a database (in my case by
sqldump
) - Cleanup database (especially table
django_migrations
) - Remove all migrations in your project
- Run
manage.py makemigrations
- Add migration that adds all data inserts from your old migrations
- Run
manage.py migrate
- Remove table
django_migrations
in your dump (maybe some otherdjango_*
tables ) - Restore your database from a dump
- [Django]-Django Query using .order_by() and .latest()
- [Django]-What is the best way to access stored procedures in Django's ORM
- [Django]-Django query get last n records
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
- [Django]-Remove leading and trailing slash / in python
- [Django]-Do we need to upload virtual env on github too?
- [Django]-Django serve static index.html with view at '/' url
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.
- [Django]-Does SQLAlchemy have an equivalent of Django's get_or_create?
- [Django]-Django: Overriding __init__ for Custom Forms
- [Django]-Django south migration – Adding FULLTEXT indexes
3
Alternatively, you can also try:
- Do
python manage.py migrate <app_name>
on the app that contains the custom user model. - 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
- [Django]-Django 1.4 Many-to-Many bulk add
- [Django]-How to copy InMemoryUploadedFile object to disk
- [Django]-Vscode html autoformat on django template
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_*
anddjango_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
andauth
apps with:
DELETE FROM django_migrations WHERE app='admin' or app='auth';
- Then simply run:
./manage.py migrate
- [Django]-Django/DRF – 405 Method not allowed on DELETE operation
- [Django]-Django template can't loop defaultdict
- [Django]-Filter on prefetch_related in Django
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)
- [Django]-Http POST drops port in URL
- [Django]-Register every table/class from an app in the Django admin page
- [Django]-Pulling data to the template from an external database with django
0
follow the below instructions
- create database buckup:
pg_dump -U user_name -d database_name –data-only > file_name.sql- go to .sql file path and rename using run the command:
sed -i ‘s/auth_user/custom_user/g’ file_name.sql- go to sql terminal run command:
=# select ‘drop table if exists "’ || tablename || ‘" cascade;’ from
pg_tables where schemaname = ‘public’;
=#\gexec- find . -path "/migrations/.py" -not -name "init.py" -delete
- find . -path "/migrations/.pyc" -delete
- python manage.py makemigrations
- python manage.py migrate
- load the .sql file to data base using this command:
psql -U user_name -d database_name -f file_name.sql
- [Django]-Django-rest-framework 3.0 create or update in nested serializer
- [Django]-Serving Media files during deployment in django 1.8
- [Django]-Passing lists or tuples as arguments in django raw 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())],
)
],
),
]
- [Django]-How to make Django's devserver public ? Is it generally possible?
- [Django]-Django template, if tag based on current URL value
- [Django]-How to read the database table name of a Model instance?
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
- [Django]-Django lazy QuerySet and pagination
- [Django]-Vagrant + Chef: Error in provision "Shared folders that Chef requires are missing on the virtual machine."
- [Django]-Creating a dynamic choice field
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.
- [Django]-Django error message "Add a related_name argument to the definition"
- [Django]-Docker – Can't access Django server
- [Django]-How do i pass GET parameters using django urlresolvers reverse
-1
Apparently nothing was incorrect with the code, i just had to drop all my user tables and run makemigration and migrate.
- [Django]-Changing Django settings at runtime
- [Django]-What is the benefit of using a HyperlinkedModelSerializer in DRF?
- [Django]-Rendering a value as text instead of field inside a Django Form
- [Django]-Django Manager Chaining
- [Django]-Django: How can I put an <a> hyperlink in a django validation error from a forms clean() method?
- [Django]-Django: Where does "DoesNotExist" come from?
-3
Remove all the migrations under Migration Directory
Now you can use makemigrations and migrate
- [Django]-Django: Reference to an outer query may only be used in a subquery
- [Django]-Django persistent database connection
- [Django]-Adding css class to field on validation error in django