159👍
I was facing a similar problem in Django 1.10 and none of the above solutions worked for me.
What eventually worked was running this command:
python manage.py migrate --fake myappname zero
This reset all migrations (to the zeroth state)
This followed by :
python manage.py migrate myappname
created the tables for me.
If you do not want to roll back to the initial(zero) state but say to the migration number 0005(the last migration that worked), you can instead do this:
python manage.py migrate --fake myappname 0005
And then proceed with the actual migrate:
python manage.py migrate myappname
More details in the docs
32👍
In my case the __init__.py
file was missing from the APP/migrations/ folder. If you don’t have one, all it needs is an empty __init__.py
file.
- [Django]-How to use refresh token to obtain new access token on django-oauth-toolkit?
- [Django]-Get user profile in django
- [Django]-Error "You're accessing the development server over HTTPS, but it only supports HTTP"
15👍
I ran into the same problem. After lots of digging, I found the solution.
I’m using django 1.11.
If you want to start-over,
1)delete all the files in your migrations folder except __init__.py
2)drop database
3)create database
4)python makemigrations
5)python migrate
if you have reset_db
, instead of 2nd and 3rd steps you can use reset_db
.
python manage.py reset_db
- [Django]-Django – How to use decorator in class-based view methods?
- [Django]-Get user profile in django
- [Django]-Django 1.5 custom User model error. "Manager isn't available; User has been swapped"
10👍
I am using MySQL and get into this issue after deleting 0001_initial.py
migration file and all the custom tables evolved from DB to try to regenerate all they…
Solved this issue simply deleting these rows in django_migrations
table…
After that, $ python manage.py migrate
command regenerates all my custom tables again.
- [Django]-Django 1.5 – How to use variables inside static tag
- [Django]-Django dynamic forms – on-the-fly field population?
- [Django]-Disable session creation in Django
8👍
Change managed = True (if it is set to False) in models.py
class Meta:
managed = False
db_table = 'table_name'
To
class Meta:
managed = True
db_table = 'table_name'
- [Django]-Django query get last n records
- [Django]-How do I use pagination with Django class based generic ListViews?
- [Django]-How to check if django template variable is defined?
6👍
I had a similar problem and just figured it out.I have multiple databases. My local one (the one not being updated) is a MySQL database. The others are MS SQL Server and MySQL. I have routers to the other databases since I do not manage them and had (in Django 1.6) used the routers to indicate allow_sync() = False. With 1.7, I changed that to allow_migrate() = False. BUT I DID NOT ADD A ROUTER FOR MY LOCAL DATABASE. The default appears to be allow_migrate() = False if there is not one. As a result, the migrations just failed silently ( Reference: https://docs.djangoproject.com/en/1.7/topics/db/multi-db/). I added a router for my local DB, setting allow_migrate() to return True and now my migrations actually create my tables.
- [Django]-Altering one query parameter in a url (Django)
- [Django]-Save base64 image in django file field
- [Django]-Creating a dynamic choice field
5👍
I had a similar issue. I did everything stated above but nothing worked. Then I realized I had not added my model name in admin.py
file in my app.
Along with everything stated above you have to also add your model name in admin.py
file. You have to add it like this:
admin.site.register(model name)
- [Django]-How to get an ImageField URL within a template?
- [Django]-How to copy InMemoryUploadedFile object to disk
- [Django]-With DEBUG=False, how can I log django exceptions to a log file
4👍
This can be very frustrating, but here is method that worked for me.
First, if you’ve deleted the migration file go ahead and create it again
python manage.py makemigrations
Then compare the migration file with the SQL raw code and if it fit then apply migration
python manage.py sqlmigrate [app_name] 0001
python manage.py migrate
or you can simply pipe it from your command line or terminal
python manage.py sqlmigrate [app_name] 0001 | [psql] db_name username
BEGIN
CREATE TABLE
ALTER TABLE
COMMIT
NOTE: In my case I’m using postgresql. Though engine is similar to other database langauge, you might not get expected result.
- [Django]-Good open source django project for learning
- [Django]-Django nested transactions – “with transaction.atomic()”
- [Django]-Django debug display all variables of a page
3👍
-
Delete existing tables of the models in MySQL database.
-
Delete migration folder under app folder.
-
Delete all relative migration records in the table
"django_migrations" from MySQL. -
Now you get clear model and database. Use
python manage.py makemigrations
andpython manage.py migrate
to create tables.
Hope to help you.
- [Django]-How do I deploy Django on AWS?
- [Django]-How to keep all my django applications in specific folder
- [Django]-How do you skip a unit test in Django?
3👍
try this one,
run,
python manage.py makemigrations app_name
above command will make migrations, if successful then run second command or
check if you have typo in Installed_app and also check for AppConfig module
python manage.py migrate app_name
if above was successful, this will create the table in db
- [Django]-_() or {% trans %} in Django templates?
- [Django]-How to get the currently logged in user's id in Django?
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
3👍
In my case just one app’s tables of project doesn’t recreate!
and this line of code recreate them and successfully run!
python manage.py migrate --run-syncdb
However I couldn’t find main reason caused this kind of problem!
- [Django]-Get protocol + host name from URL
- [Django]-How to use curl with Django, csrf tokens and POST requests
- [Django]-Django Forms and Bootstrap – CSS classes and <divs>
2👍
This solved the problem for me (I am using MySQL workbench by the way):
- Run this sql:
SET FOREIGN_KEY_CHECKS = 0;
- Select all the tables in your django database (click on the first table, then press and hold shift, then click on the last table). Then right click and choose “Drop n tables” (where n is the number of tables you just selected)
- then run
python manage.py migrate
- Finally restore foreign key check settings by running this sql:
SET FOREIGN_KEY_CHECKS = 1;
Note: Before taking this drastic measure, I tried what Paulo Pessoa said in his comment, but still I got “No migrations to apply.” messages. However, this solved the issue.
- [Django]-Django: Filter a Queryset made of unions not working
- [Django]-Request.POST.get('sth') vs request.POST['sth'] – difference?
- [Django]-No module named 'polls.apps.PollsConfigdjango'; Django project tutorial 2
2👍
Problem: : When you apply migrations in django for the first time, django creates table of that model in database and marks somewhere in its own file(class):
`initial = True`
-
When you then tries to alter the schema of that table it firstly checks
ifinitial = True
-
if an initial class attribute isn’t found, a migration will be considered “initial”
-
In case the
initial = True
we need to usepython manage.py migrate --fake-initial
For an initial migration Django checks that all of those tables already exist in the database and fake-applies the migration if so. Similarly, for an initial migration that adds one or more fields Django checks that all of the respective columns already exist in the database and fake-applies the migration if so.
Fake initial migration uses both CreateModel() and AddField() methods.
Solution:
>> python manage.py makemigrations <AppName>
>> python manage.py migrate --fake-initial
- [Django]-How do I change the range of the x-axis with datetime?
- [Django]-Get path of virtual environment in pipenv
- [Django]-How do I reuse HTML snippets in a django view
2👍
- If you want to do it only for your application not from all the apps then Clear your application migrations records from ‘django_migrations’ table in your DB.
- Python manage.py makemigrtions
- python
- [Django]-Django – How to use decorator in class-based view methods?
- [Django]-Aggregating save()s in Django?
- [Django]-Django: Filter a Queryset made of unions not working
1👍
To avoid deleting critical databases, you may also consider silencing properties
below the Class Meta:
for example this model:
class Blog(models.Model):
category = models.CharField(max_length=100)
title = models.CharField(max_length=100)
date_added = models.DateTimeField()
merits = models.CharField(max_length=300, blank=True)
demerits = models.CharField(max_length=300, blank=True)
class Meta:
managed = True
db_table = 'weblog'
verbose_name_plural = "Blog"
@property
def content_min(self):
return truncatechars(self.content, 50)
You can then run makemigrations
and migrate
and your table will be created.
- [Django]-Alowing 'fuzzy' translations in django pages?
- [Django]-How to repeat a "block" in a django template
- [Django]-How do you configure Django for simple development and deployment?
1👍
Check if you have added your created app to you installed apps under settings.py
.
The list should seem like this:
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages','django.contrib.staticfiles',
'YourCreatedApp',
]
- [Django]-Django: Fat models and skinny controllers?
- [Django]-Django – Reverse for '' not found. '' is not a valid view function or pattern name
- [Django]-Inline in ModelForm
0👍
- Delete database
- delete
migration
folder - run
migrate
command - run
makemigrations
command - run
migrate
command
It will create all tables perfectly
- [Django]-Storing an Integer Array in a Django Database
- [Django]-Django: Get list of model fields?
- [Django]-Using a UUID as a primary key in Django models (generic relations impact)
0👍
- Change from sqlite3 to mysql in settings.py
- Make sure you have correct information regarding database name and username-password
- Delete existing migration
- Make migration
- And then migrate
- [Django]-Efficient way to update multiple fields of Django model object
- [Django]-How to duplicate virtualenv
- [Django]-Displaying a Table in Django from Database
- [Django]-What does "'tests' module incorrectly imported" mean?
- [Django]-Django Rest Framework — no module named rest_framework
- [Django]-Django-taggit – how do I display the tags related to each record
0👍
I had a similar issue, the connection with DB was set correctly as all the django admin tables were created on DB side. However, no models appeared in models.py
What worked for me is running in the console:
python manage.py inspectdb > models.py
which wrote everything into a new models.py file which then I replaced with the one I had in the app folder. Then I could alter the
managed = False
into
managed = True
here the link to the documentation: https://docs.djangoproject.com/en/3.1/howto/legacy-databases/
- [Django]-Can we append to a {% block %} rather than overwrite?
- [Django]-DatabaseError: current transaction is aborted, commands ignored until end of transaction block?
- [Django]-How to get the current url namespace using Django?
0👍
If you are a begginer like me make sure your classes extend models.Model. Then makemigrations and migrate.
class Cook(models.Model):
email = models.Field()
- [Django]-What's the best way to migrate a Django DB from SQLite to MySQL?
- [Django]-How to run celery as a daemon in production?
- [Django]-Using Django time/date widgets in custom form
0👍
I solved a similar problem by doing this:
- Delete all migration files and pycache so what retains is
init.py
- Comment all implementations of that table in models, serializers, admin, urls and views
- Do
python manage.py makemigrations
- Do
python manage.py migrate
- Then, uncomment all implementations of that table in models, serializers, admin, urls and views
- Then, do
python manage.py makemigrations
- Then, do
python manage.py migrate
- [Django]-Simple Subquery with OuterRef
- [Django]-Adding new custom permissions in Django
- [Django]-Object does not support item assignment error
0👍
To elaborate on @Leman-Kirme ‘s answer.
I had a similar problem where the table for the model I added into models.py
of one of my apps wouldn’t get created when making and applying migrations. I tried different solutions but nothing seemed to work and I really didn’t want to flush my databases. So what I did was:
- Delete all the files in the migrations folder except for
_init_.py
- Delete all records in databases’
django_migrations
tables. - Manually make a migration file (copied from another project and changed the content so that migration would only make a model that I was having troubles with). Please, note, that it seems like it should be initial migration, i.e.
0001_initial.py
- Run it.
- Voila, here comes the table!
- If you want / need, instead of deleting previous migrations’ files and records in the databases, you could backup them and restore afterwards. You gonna need to edit name of your manually-created migration from
0001_initial
to something like<number_of_existing_migrations>_fix
That worked for me (but I ignored step 6), I hope someone finds this useful as well!
- [Django]-How can I retrieve a list of field for all objects in Django?
- [Django]-Where to put Django startup code?
- [Django]-Django: Redirect logged in users from login page
0👍
Gist: => Delete entry from django_migrations and run the migrate command again.
This answer takes help from other answers, but still writing as there are different cases and my answer might help in your case.
After creating migration, I think by mistake I ran the command python manage.py migrate campaign --fake
I am not sure if it did some wrong thing, so now running python manage.py migrate campaign
was not creating table
So what solved for me is–
in mysql shell run
select * from django_migrations;
Note the id of last migration which is creating problem in my case it was 62
delete from django_migrations where id = 62
Now I ran the migration again, and it worked this time. with command
python manage.py migrate campaign
i.e. required table was created as a result of applying migration
- [Django]-What is the advantage of Class-Based views?
- [Django]-How would you create a 'manual' django migration?
- [Django]-How to set up a PostgreSQL database in Django
0👍
The problem I discovered working with Postgres is that I had not set the schema. I the original question is one of those gotchas that may have a number of different answers, so if the other answers are not working for you just check this.
The "problem" is that Postgres has an additional "namespace" layer which means you can specify the database but there can still be a whole set of tables, still in the same database, but in another schema
or namespace
.
The tables in this schema may be unreachable because the user being used to connect does not have permissions, or in fact the schema has been specified, but the tables were created in a different schema, or even you haven’t specified the schema this time and are looking in the public
schema while the tables have been created in another schema.
So the solution is to set the schema correctly, to what you intend, in every location and place that you use it. This boils down to correct database settings in all the settings files you are using, and logging in to the right schema and user when you inspect the database manually.
For example:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'OPTIONS': {'options': f'-c search_path={"foobar"}'},
'NAME': 'foo',
'USER': 'bar',
'PASSWORD': 'barpass',
'HOST': 'baz.example.com',
'PORT': 5432,
},
}
The database name here is foo
, the username is bar
and the schema name is foobar
. Adding this line to the OPTIONS
parameter defaults the schema for all operations.
For other usage, within Postgres, you can display the current search_path
, and alter it for the current session, or "permanently" for the database:
SHOW search_path;
SET search_path=foobar,public;
ALTER DATABASE foo SET search_path TO foobar;
If your problem was that Django was creating your tables, but just in the wrong schema or under different permissions, I hope this has resolved your issue.
- [Django]-Django – Login with Email
- [Django]-How to mock users and requests in django
- [Django]-Django serializer inherit and extend fields
0👍
This kind-of thing was happening to me when I would try to reset my DB. Nothing else would work to get django to recognize my tables except:
python manage.py migrate --run-syncdb
- [Django]-How to store a dictionary on a Django Model?
- [Django]-Django models avoid duplicates
- [Django]-How to know current name of the database in Django?
0👍
In my case those solutions didn’t work to me
I have to:
- Create a new app:
py manage.py startapp new_app_name
- Copy all the files in my new app
- Run:
py manage.py makemigrations
- Run:
py manage.py migrate
It works to me, I hope it could be useful for you too
- [Django]-Django: using blocks in included templates
- [Django]-Django REST Framework: how to substitute null with empty string?
- [Django]-How to pass multiple values for a single URL parameter?
0👍
In my case, I accidentally deleted the migrations folder from the app. So; re-creating the folder and adding the __init__.py
file inside it has fixed the problem
- [Django]-Gunicorn Connection in Use: ('0.0.0.0', 5000)
- [Django]-Exclude a field from django rest framework serializer
- [Django]-Django serializer Imagefield to get full URL
-1👍
Below commands worked for me
python manage.py makemigrations app_name
python manage.py migrate app_name
- [Django]-Django Forms and Bootstrap – CSS classes and <divs>
- [Django]-Where to put business logic in django
- [Django]-How can I programmatically obtain the max_length of a Django model field?
- [Django]-How to add multiple objects to ManyToMany relationship at once in Django ?
- [Django]-Race conditions in django
- [Django]-A Better Django Admin ManyToMany Field Widget