I’m building a fairly simple application, research, in my Django project that uses Django-CMS. (It’s my first ground-up attempt at a project/application.) Its main purpose is to store various intellectual assets (i.e article, book, etc. written by a researcher).
The problem is that when I point the browser to /research/
I get an error saying that the table 'research_journal' doesn't exist ("no such table")
.
I’m using Djnago 1.6.5 with a sqlite3 database.
Looking at python manage.py sql research
yields:
BEGIN;
CREATE TABLE "research_researchbase" (
"id" integer NOT NULL PRIMARY KEY,
"pub_date" datetime NOT NULL,
"authors" varchar(200) NOT NULL,
"year" varchar(25) NOT NULL,
"title" varchar(200) NOT NULL,
"subtitle" varchar(200) NOT NULL,
"image_id" integer NOT NULL REFERENCES "filer_image" ("file_ptr_id"),
"link" varchar(200) NOT NULL
)
;
CREATE TABLE "research_journal" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"journal" varchar(200) NOT NULL,
"abstract" text NOT NULL,
"citation" varchar(200) NOT NULL
)
;
CREATE TABLE "research_encyclopedia_chapter" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"encyclopedia" varchar(200) NOT NULL,
"publisher" varchar(200) NOT NULL,
"summary" varchar(200) NOT NULL
)
;
CREATE TABLE "research_book" (
"researchbase_ptr_id" integer NOT NULL PRIMARY KEY REFERENCES "research_researchbase" ("id"),
"publisher" varchar(200) NOT NULL,
"summary" varchar(200) NOT NULL
)
;
COMMIT;
I’ve run python manage.py migrate research
and get:
/Users/XXX/Documents/repos/sfs/env/lib/python2.7/site-packages/app_data/fields.py:2: DeprecationWarning: django.utils.simplejson is deprecated; use json instead.
from django.utils import simplejson as json
Running migrations for research:
- Nothing to migrate.
- Loading initial data for research.
Installed 0 object(s) from 0 fixture(s)
I’ve run python manage.py syncdb
and get the following:
Syncing...
Creating tables ...
Installing custom SQL ...
Installing indexes ...
Installed 0 object(s) from 0 fixture(s)
Synced:
> djangocms_admin_style
> django.contrib.auth
> django.contrib.contenttypes
> django.contrib.sessions
> django.contrib.admin
> django.contrib.sites
> django.contrib.sitemaps
> django.contrib.staticfiles
> django.contrib.messages
> mptt
> south
> sekizai
> django_select2
> hvad
Not synced (use migrations):
- djangocms_text_ckeditor
- cms
- menus
- djangocms_style
- djangocms_column
- djangocms_file
- djangocms_flash
- djangocms_googlemap
- djangocms_inherit
- djangocms_link
- djangocms_picture
- djangocms_teaser
- djangocms_video
- reversion
- polls
- djangocms_polls
- aldryn_blog
- easy_thumbnails
- filer
- taggit
- research
(use ./manage.py migrate to migrate these)
Here’s the models.py
:
from django.db import models
from django.utils import timezone
from filer.fields.image import FilerImageField
import datetime
class ResearchBase(models.Model):
pub_date = models.DateTimeField('date published')
authors = models.CharField(max_length=200)
year = models.CharField(max_length=25)
title = models.CharField(max_length=200)
subtitle = models.CharField(max_length=200, blank=True)
image = FilerImageField()
link = models.CharField(max_length=200, blank=True)
def __unicode__(self):
return self.title
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)
class Journal(ResearchBase):
journal = models.CharField(max_length=200)
abstract = models.TextField()
citation = models.CharField(max_length=200)
class Encyclopedia_Chapter(ResearchBase):
encyclopedia = models.CharField(max_length=200)
publisher = models.CharField(max_length=200)
summary = models.CharField(max_length=200)
class Book(ResearchBase):
publisher = models.CharField(max_length=200)
summary = models.CharField(max_length=200)
Here’s my views.py
(note that I am passing two objects through render, ignore the fact that I have yet to include the class Books in the whole deal):
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from research.models import Journal, Encyclopedia_Chapter, Book
def research_index(request):
latest_journal_list = Journal.objects.order_by('-pub_date')[:5]
latest_chapter_list = Encyclopedia_Chapter.objects.order_by('-pub_date')[:5]
context = {
'latest_journal_list': latest_journal_list,
'latest_chapter_list': latest_chapter_list
}
return render(request, 'research/index.html', context)
def journal_detail(request, journal_id):
journal = get_object_or_404(Journal, pk=journal_id)
return render(request, 'research/journal_detail.html', {'journal': journal})
def chapter_detail(request, chapter_id):
chapter = get_object_or_404(Encyclopedia_Chapter, pk=chapter_id)
return render(request, 'research/chapter_detail.html', {'chapter': chapter})
Here’s the application’s url.py
:
from django.conf.urls import patterns, url
from research import views
urlpatterns = patterns('',
url(r'^$', views.research_index, name='research'),
url(r'^(?P<journal_id>d+)/$', views.journal_detail, name='journal_detail'),
url(r'^(?P<chapter_id>d+)/$', views.chapter_detail, name='chapter_detail'),
)
Here’s the index.html
template:
{% extends 'research/base.html' %}
{% block research_content %}
<div class="container">
<div class="row featurette">
<h3 id="research">Peer-reviewed Journal Articles</h3>
{% if latest_journal_list %}
<ul id="research">
{% for journal in latest_journal_list %}
<li id="research">
<img src="{{ journal.image.url }}" id="research">
<h4>{{ journal.journal }}</h4>
<h5>{{ journal.title }}</h5>
<a href="{% url 'research:journal_detail' journal.id %}">Read More</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No journals are available.</p>
{% endif %}
</div>
<div class="row featurette">
<h3 id="research">Encyclopedia Chapters</h3>
{% if latest_chapter_list %}
<ul id="research">
{% for chapter in latest_chapter_list %}
<li id="research">
<img src="{{ chapter.image.url }}" id="research">
<h4>{{ chapter.journal }}</h4>
<h5>{{ chapter.title }}</h5>
<a href="{% url 'research:chapter_detail' chapter.id %}">Read More</a>
</li>
{% endfor %}
</ul>
{% else %}
<p>No encyclopedia chapters are available.</p>
{% endif %}
</div>
</div>
{% endblock %}
Just in case it matters, here’s my cms_app.py
:
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from django.utils.translation import ugettext_lazy as _
class ResearchApp(CMSApp):
name = _("Research App")
urls = ["research.urls"]
app_name = "research"
apphook_pool.register(ResearchApp)
In Django I added models into models.py
. After manage.py makemigrations
, manage.py migrate
raised this exception:
django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile
I removed all old migrations and run makemigrations
and migrate
again which seemed to work. It didn’t help because when I click User customer profiles
of User translator profiles
it raises exception:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/
Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:Python27libsite-packagesdjangocontribadminoptions.py" in wrapper
618. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoviewsdecoratorscache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangocontribadminsites.py" in inner
233. return view(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:Python27libsite-packagesdjangocontribadminoptions.py" in changelist_view
1550. self.list_max_show_all, self.list_editable, self)
File "C:Python27libsite-packagesdjangocontribadminviewsmain.py" in __init__
82. self.get_results(request)
File "C:Python27libsite-packagesdjangocontribadminviewsmain.py" in get_results
177. result_count = paginator.count
File "C:Python27libsite-packagesdjangocorepaginator.py" in _get_count
72. self._count = self.object_list.count()
File "C:Python27libsite-packagesdjangodbmodelsquery.py" in count
318. return self.query.get_count(using=self.db)
File "C:Python27libsite-packagesdjangodbmodelssqlquery.py" in get_count
466. number = obj.get_aggregation(using, ['__count'])['__count']
File "C:Python27libsite-packagesdjangodbmodelssqlquery.py" in get_aggregation
447. result = compiler.execute_sql(SINGLE)
File "C:Python27libsite-packagesdjangodbmodelssqlcompiler.py" in execute_sql
840. cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbutils.py" in __exit__
98. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendssqlite3base.py" in execute
318. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile
models.py:
from django.db import models
from django.contrib.auth.models import User
class Language(models.Model):
shortcut = models.CharField(max_length=6)
name = models.CharField(max_length=50)
price_per_sign = models.FloatField()
class UserTranslatorProfile(models.Model):
user = models.OneToOneField(User)
languages = models.ManyToManyField(Language)
price_per_word = models.FloatField()
class UserCustomerProfile(models.Model):
user = models.OneToOneField(User)
admin.py:
from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))
What is the problem?
Привет, я пытаюсь освоить джанго и нахожусь на этапе добавления тестового «продукта» в режиме админа.
Зашел в 127.0.0.1:8000/admin далее в разделе Products который создал ранее в admin.py
from django.contrib import admin
from .models import Product
admin.site.register(Product)
а также в models.py
class Offer(models.Model):
code = models.CharField(max_length=10)
description = models.CharField(max_length=255)
discount = models.FloatField()
… нажимаю + Add
далее заполняю все необходимые поля, жму на Save и … получаю вот такую ошибку:
OperationalError at /admin/products/product/add/
no such table: main.auth_user__old
Request Method: POST
Request URL: http://127.0.0.1:8000/admin/products/product/add/
Django Version: 2.1
Exception Type: OperationalError
Exception Value:
no such table: main.auth_user__old
Exception Location: C:UsersdmitrPycharmProjectsPyShopvenvlibsite-packagesdjangodbbackendssqlite3base.py in execute, line 296
Python Executable: C:UsersdmitrPycharmProjectsPyShopvenvScriptspython.exe
Python Version: 3.7.4
Python Path:
['C:\Users\dmitr\PycharmProjects\PyShop',
'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\python37.zip',
'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\DLLs',
'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32\lib',
'C:\Users\dmitr\AppData\Local\Programs\Python\Python37-32',
'C:\Users\dmitr\PycharmProjects\PyShop\venv',
'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages',
'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages\setuptools-39.1.0-py3.7.egg',
'C:\Users\dmitr\PycharmProjects\PyShop\venv\lib\site-packages\pip-10.0.1-py3.7.egg']
Server time: Sat, 23 May 2020 22:35:43 +0000
посмотрел на стэке (https://stackoverflow.com/questions/36123312/djang…) — там говорят что всего лишь надо
python manage.py migrate
python manage.py makemigrations
python manage.py migrate
Но это не помогает…
Проблема какая-то совсем простая но не пойму в чем дело.
Спасибо!
Loading
Problem Description:
In Django I added models into models.py
. After manage.py makemigrations
, manage.py migrate
raised this exception:
django.db.utils.OperationalError: no such table: auth_test_usertranslatorprofile
I removed all old migrations and run makemigrations
and migrate
again which seemed to work. It didn’t help because when I click User customer profiles
of User translator profiles
it raises exception:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/auth_test/usertranslatorprofile/
Django Version: 1.8.7
Python Version: 2.7.10
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'auth_test')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware')
Traceback:
File "C:Python27libsite-packagesdjangocorehandlersbase.py" in get_response
132. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:Python27libsite-packagesdjangocontribadminoptions.py" in wrapper
618. return self.admin_site.admin_view(view)(*args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoviewsdecoratorscache.py" in _wrapped_view_func
57. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangocontribadminsites.py" in inner
233. return view(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapper
34. return bound_func(*args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in _wrapped_view
110. response = view_func(request, *args, **kwargs)
File "C:Python27libsite-packagesdjangoutilsdecorators.py" in bound_func
30. return func.__get__(self, type(self))(*args2, **kwargs2)
File "C:Python27libsite-packagesdjangocontribadminoptions.py" in changelist_view
1550. self.list_max_show_all, self.list_editable, self)
File "C:Python27libsite-packagesdjangocontribadminviewsmain.py" in __init__
82. self.get_results(request)
File "C:Python27libsite-packagesdjangocontribadminviewsmain.py" in get_results
177. result_count = paginator.count
File "C:Python27libsite-packagesdjangocorepaginator.py" in _get_count
72. self._count = self.object_list.count()
File "C:Python27libsite-packagesdjangodbmodelsquery.py" in count
318. return self.query.get_count(using=self.db)
File "C:Python27libsite-packagesdjangodbmodelssqlquery.py" in get_count
466. number = obj.get_aggregation(using, ['__count'])['__count']
File "C:Python27libsite-packagesdjangodbmodelssqlquery.py" in get_aggregation
447. result = compiler.execute_sql(SINGLE)
File "C:Python27libsite-packagesdjangodbmodelssqlcompiler.py" in execute_sql
840. cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
79. return super(CursorDebugWrapper, self).execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbutils.py" in __exit__
98. six.reraise(dj_exc_type, dj_exc_value, traceback)
File "C:Python27libsite-packagesdjangodbbackendsutils.py" in execute
64. return self.cursor.execute(sql, params)
File "C:Python27libsite-packagesdjangodbbackendssqlite3base.py" in execute
318. return Database.Cursor.execute(self, query, params)
Exception Type: OperationalError at /admin/auth_test/usertranslatorprofile/
Exception Value: no such table: auth_test_usertranslatorprofile
models.py:
from django.db import models
from django.contrib.auth.models import User
class Language(models.Model):
shortcut = models.CharField(max_length=6)
name = models.CharField(max_length=50)
price_per_sign = models.FloatField()
class UserTranslatorProfile(models.Model):
user = models.OneToOneField(User)
languages = models.ManyToManyField(Language)
price_per_word = models.FloatField()
class UserCustomerProfile(models.Model):
user = models.OneToOneField(User)
admin.py:
from django import forms
from .models import Language
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class FreelancerRegistrationForm(forms.Form):
language = forms.ModelChoiceField(queryset=Language.objects.all().order_by('shortcut'))
What is the problem?
Solution – 1
I solved the same problem with these steps :
- Delete your database (
db.sqlite3
in my case) in your project directory - Remove everything from
__pycache__
folder under your project subdirectory - For the application you are trying to fix, go to the folder and clear
migrations
and__pycache__
directories
When you are sure you have cleared all the above files, run:
python manage.py makemigrations
python manage.py migrate
I hope this helps.
Solution – 2
Another case wihch can generate the no such table error. If your views.py or similar executes code that tries to access the DB when imported, i.e. importing views.py has side effects, then starting from scratch won’t work.
This happens when your code was working with an existing DB, and now you’re trying to start without a DB. Just change views.py so it can be imported without side effects. If you don’t want to fix the design, do something like:
from django.db.utils import OperationalError
format_list = [('', '(all)')]
geom_type_list = [('', '(all)')]
try:
format_list.extend([(i[0],i[0])
for i in Format.objects.values_list('name')])
geom_type_list.extend([(i[0],i[0])
for i in Geom_type.objects.values_list('name')])
except OperationalError:
pass # happens when db doesn't exist yet, views.py should be
# importable without this side effect
Solution – 3
Adding to terry_brown’s answer, this is what cause my problems. I had a custom user model with ForeignKey to another model. And I set defaults to first object in the DB. It worked when I had the data in the database. But when I started from scratch, it didn’t work because it was executed immediately when imported (so not even migration went through).
class User(AbstractBaseUser, PermissionsMixin):
subscription_plan = models.ForeignKey(SubscriptionPlan, default=SubscriptionPlan.objects.first().id)
I had to sacrifice that default
(commenting it out).
UPDATE:
A better solution would be to prepopulate your database with initial migration or fixtures.
Solution – 4
Maybe out of time but…I have same problem when I tried to “clone” Django 1.11 installation into other directory and then with initial try to manage makemigrations.
I solve the problem following way:
- settup initial Django installation and creating main application by:
django-admin.py startproject app_name
-
initial migrations
manage makemigrations, manage migrate -
Setup the superuser:
manage createsuperuser
-
copy all files and directories (Django applications) except the urls.py and settings.py in main directory
-
Added all apps into INSTALLED_APPS
-
manage makemigrations, manage migrate
-
Copied settings.py and urls.py from source Django application directory
Thats it no errors and all is working fine.
Petr
Solution – 5
If someone else has this problem and the accepted solution is not working, have a look at your db path,
the db path should be absolute path,
'NAME': '/pathto-db/default.db',
Link
Solution – 6
run below command. It solves me once this issue
manage.py migrate –run-syncdb
Solution – 7
To solve it I did this (on Ubuntu, you’ll need to adapt the commands for Windows):
1. Remove all the migration files
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
2. Delete db.sqlite3
rm db.sqlite3
3. Create and run the migrations:
python manage.py makemigrations
python manage.py migrate
4. Sync the database:
manage.py migrate --run-syncdb
Bit of a pain as you need to delete your database, but fine for a test system.
Got all but the final step from this generally excellent resource: https://simpleisbetterthancomplex.com/tutorial/2016/07/26/how-to-reset-migrations.html
Solution – 8
While running any management command “django.contrib.admin” automatically attempts to discover and admin.py modules in installed apps.
If there is a code related to database, it runs automatically and tries to load data from database when it can not find data related table in database throw this Error.
To fix this error just change "django.contrib.admin"
in INSTALLED_APPS
to "django.contrib.admin.apps.SimpleAdminConfig"
, it will prevent “django.contrib.admin” from auto discovering and running admin modules.
django.contrib.admin automatically performs auto discovery of admin modules in installed applications. To prevent it, change your INSTALLED_APPS to contain ‘django.contrib.admin.apps.SimpleAdminConfig’ instead of ‘django.contrib.admin’.
https://docs.djangoproject.com/en/3.0/ref/applications/#troubleshooting
Solution – 9
If none of the above solution worked for you then add the appname
along with the makemigration
and migrate
command.
makemigration login
migrate login
That might help you to figure out the problem.
Solution – 10
Follow this steps to get fixed this issue.
python manage.py migrate --fake APPNAME zero
This will make your migration to fake. Now you can run the migrate script
python manage.py migrate APPNAME
OR
python manage.py migrate
Tables will be created and you solved your problem.. Cheers!!!
Solution – 11
You don’t need views to makemigrations. Comment out all references to other apps from urls.py, clear db and old migrations, run makemigrations, and comment your urls.py back in. Worked for me.
Solution – 12
I read the above Answers given by other teams.
Majorly were asking to delete SQLite(DB) and reset the «migrations» folder.
If you are working in a production environment then this will not be the right choice.
python manage.py migrate --fake APPNAME zero
python manage.py migrate APPNAME
python manage.py makemigrations APPNAME
python manage.py migrate APPNAME
These four steps are enough to solve this issue.
Solution – 13
I got this error while creating a model.
I opened the db.sqlite3 file and created a table for the model using SQLite DB Browser. Then I created a migration and fake migrated it. Don’t know what caused the issue but this workaround helped.
Solution – 14
I had the same problem.
None of the above solutions worked for me.
It all probably started when I added a new model, had a few objects in the database and then I changed model’s name.
I needed to delete the whole model from my app and then run app’s admin page. Then I restored the model by clicking ctrl + z in all files from which I deleted it and finally I was able to run makemigrations and migrate commands.
Solution – 15
would you delete a production bank?
I saw that many have the sqlite deleted, but if it is a production bank?
solution to delete data from django_migrations table less contenttypes
already in the table django_content_type you remotely app_label
inside the migrations folder deletes everything but init.py
python manage.py makemigrations
python manage.py migrate –fake
that’s how I solved the app duplication problems (I had two apps with the same name after installing a plugin) and django created the missing tables, among other things.
in my normally functional case
Solution – 16
I was facing the same error. The steps I used to solve this issue is:
-
Make sure that there’s
migrations
folder inside your app. If there isn’t any, create themigrations
folder inside the app folder, and then create__init__.py
file inside the folder. -
If the
migrations
folder is already there, then delete all themigration files
. -
Delete the database file which is by default
db.sqlite3
. -
Run the command
python manage.py makemigrations
-
python manage.py migrate
Solution – 17
The only way to fix my error was commenting out every single file. This error might occur while a file thinks the database is not empty, or that it actually exists.
I just commented out the entire project, migrated, uncommented the models.py file, migrated again, uncommented the entire project. I have no idea why it worked.
Solution – 18
With same error and without removing database:
- remove migrations
- remove
__pychache__
python manage.py makemigrations --empty alias
python manage.py makemigrations alias
python manage.py migrate alias zero
- remove again migrations
- remove again
__pycache__
python manage.py makemigrations
python manage.py migrate alias zero
Where alias is the app name.
Solution – 19
If you have deleted the DB and migrating now this will happens.
For eg if your error says no such table table1
then
- python manage.py makemigrations
- python manage.py migrate
- python manage.py table1 app1
Here table1 is the name of the table and app1 is the Django app name where the table1 model exists.
Solution – 20
Using Django, I had to perform:
python manage.py migrate --run-syncdb
Solution – 21
This error is happening because of the database of Django , this is not user fault. Its easiest solution is create new app with different name .Then create same models and then run python manage.py makemigrations and then migrate. By doing this your error should be solved
Solution – 22
I know this commonly solved by deleting de sqlite3 DB that is used in the development process.
Also, I know this question is currently solved, but I want to leave my case here as an alternative.
Sometimes while we are programming we change a lot of things in our models. When we run python manage.py makemigrations
a file is created inside of our app folder/migrations
. And when we run python manage.py migrate
a record in the table django_migrations is created. this record contains 3 fields we must check in detail:
-
1 – name (this is the file name created in the migrations app folder)
-
2 – app (this is the name of our app. Also works like a namespace to prevent conflicts)
-
3 – applied (this is the date-time when the migration was executed).
If you’ve modified your model previously, you should have several files inside migrations (amount accordingly with the times you’ve executed makemigrations on every change), in my case I wanted to erase these files just to have only one migration file.
The problem with this is that when makemigrations was run again it creates a file 0001_initial.py. If you remember the table django_migrations contains a log of this file, this is to prevent the execution of migrations that already have been done.
If this is your case, you would erase the records of your app migrations from this table.
Solution – 23
I did some alterations in my database and was facing the same issue. None of solutions worked for me so after spending hours i finally decided to delete the «db.sqlite3» file and runs the makemigrations and migrate commands. After it worked fine. But this solution is not a good one to use immediately, use it only when you are out of options.
Solution – 24
I faced the same problem. I removed all migrations and run this command
python manage.py makemigrations
python manage.py migrate --run-syncdb
It worked for me and the data was also safe (I didn’t lose any)
Solution – 25
Maybe migrations Folder was not created:
python manage.py makemigrations app_name
python manage.py migrate
Solution – 26
I recently had a problem with this and used the @adam post to resolve my issue. I just wanted to amend his post and say that, for me in windows 10 using git bash, I had to do all of this from the venv, and then after I removed the migration files and the DB I had to pip uninstall django
and pip install django
before making the migrations.