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)
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)
I am not sure how to fix this issue
I have no idea why I am getting this error when I try to runserver:
Performing system checks...
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x1085589b0>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper
fn(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run
self.check_migrations()
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
self.loader = MigrationLoader(self.connection)
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 184, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations
self.ensure_schema()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 165, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 138, in _cursor
self.ensure_connection()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 122, in connect
self.connection = self.get_new_connection(conn_params)
File "/Library/Python/2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 134, in get_new_connection
return Database.connect(**conn_params)
File "/Library/Python/2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?
When I try to connect to postgres:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'beerad',
'USER': 'bli1',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
I am not sure how to fix this issue
I have no idea why I am getting this error when I try to runserver:
Performing system checks...
System check identified no issues (0 silenced).
Unhandled exception in thread started by <function wrapper at 0x1085589b0>
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/django/utils/autoreload.py", line 222, in wrapper
fn(*args, **kwargs)
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run
self.check_migrations()
File "/Library/Python/2.7/site-packages/django/core/management/commands/runserver.py", line 159, in check_migrations
executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
File "/Library/Python/2.7/site-packages/django/db/migrations/executor.py", line 17, in __init__
self.loader = MigrationLoader(self.connection)
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 49, in __init__
self.build_graph()
File "/Library/Python/2.7/site-packages/django/db/migrations/loader.py", line 184, in build_graph
self.applied_migrations = recorder.applied_migrations()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations
self.ensure_schema()
File "/Library/Python/2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema
if self.Migration._meta.db_table in self.connection.introspection.get_table_list(self.connection.cursor()):
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 165, in cursor
cursor = self.make_debug_cursor(self._cursor())
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 138, in _cursor
self.ensure_connection()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 133, in ensure_connection
self.connect()
File "/Library/Python/2.7/site-packages/django/db/backends/__init__.py", line 122, in connect
self.connection = self.get_new_connection(conn_params)
File "/Library/Python/2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 134, in get_new_connection
return Database.connect(**conn_params)
File "/Library/Python/2.7/site-packages/psycopg2/__init__.py", line 164, in connect
conn = _connect(dsn, connection_factory=connection_factory, async=async)
django.db.utils.OperationalError: could not connect to server: Connection refused
Is the server running on host "127.0.0.1" and accepting
TCP/IP connections on port 5432?
When I try to connect to postgres:
psql: could not connect to server: No such file or directory
Is the server running locally and accepting
connections on Unix domain socket "/tmp/.s.PGSQL.5432"?
settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'beerad',
'USER': 'bli1',
'PASSWORD': '',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
Для нового проекта, нового приложения при миграции базы данных были выполнены следующие две команды:
python manage.py makemigrations teacher_app, первый шаг успешен
python manage.py migrate teacher_app, второй шаг завершился неудачно с django.db.utils.OperationalError: нет такой таблицы: django_content_type
Решение:
python manage.py makemigrations teacher_app
python manage.py migrate
причина:
migrate,Быть ответственным заВерныйINSTALLED_APPSПриложения вмигрировать.makemigrations, Отвечает за создание новой миграции на основе модификации вашей моделиsqlmigrate, Показать перенесенный оператор sqlshowmigrations, В котором перечислены миграция и статус проекта.
Python manger.py makemigrations: в текущем каталоге будет создана папка миграции. Содержимое папки — это содержимое, которое будет выполняться базой данных. Будут сгенерированы операторы SQL. Для просмотра определенных операторов SQL можно использовать приложение python manger.py sqlmigrate 0001.
python manager.py migrate: выполнить созданный ранее файл миграции, применить действие к файлу базы данных и сгенерировать таблицу.
python manage.py migrate app_name: выполняйте файл миграции только в приложении app_name, создайте соответствующую таблицу и не выполняйте другие файлы миграции. Но после создания нового проекта некоторые файлы миграции будут автоматически сгенерированы для нас.Только после того, как эти файлы миграции по умолчанию будут выполнены и таблицы по умолчанию (такие как: django_content_type, auth_permission и т. Д.), Мы сможем выполнить наши собственные миграции. Файл для создания нужной нам таблицы.
Конкретный процесс решения проблемы.
Моя среда: Centos6.8 + anaconda + pycharm + python3.7 + Django1.8
Это процесс создания моего проекта:
1. Создайте проект
(Django) [[email protected] Django]# django-admin startproject teacher
(Django) [[email protected] Django]# cd teacher
(Django) [[email protected] teacher]# python manage.py startapp teacher_app
2. Напишите класс в файле models.py приложения teacher_app.
from django.db import models
# Create your models here.
class Teacher(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField()
address = models.CharField(max_length=20)
email = models.CharField(max_length=20)
def __str__(self):
return self.name
3. Добавьте приложение в настройку
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'teacher_app',
)
4. Выполните миграцию базы данных:
(Django) [[email protected] teacher]# python manage.py makemigrations teacher_app
Migrations for ‘teacher_app’:
0001_initial.py:
— Create model Teacher
(Django) [[email protected] teacher]# python manage.py migrate teacher_app
Второй шаг не удался. Сообщение об ошибке: Django.db.utils.OperationalError: нет такой таблицы: django_content_type,
«Error creating new content types. Please make sure contenttypes «
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.
Конкретное сообщение об ошибке:
(Django) [[email protected] teacher]# python manage.py makemigrations teacher_app
Migrations for 'teacher_app':
0001_initial.py:
- Create model Teacher
(Django) [[email protected] teacher]# python manage.py migrate teacher_app
Operations to perform:
Apply all migrations: teacher_app
Running migrations:
Rendering model states... DONE
Applying teacher_app.0001_initial... OK
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 65, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 328, in get
num = len(clone)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __len__
self._fetch_all()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 238, in iterator
results = compiler.execute_sql()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 225, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/sql.py", line 280, in emit_post_migrate_signal
using=db)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 82, in create_permissions
ctype = ContentType.objects.db_manager(using).get_for_model(klass)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 78, in get_for_model
"Error creating new content types. Please make sure contenttypes "
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.
В сообщении об ошибке мне предлагалось убедиться, что типы содержимого были перенесены при миграции базы данных. Затем я начал перенос типов содержимого, но по-прежнему сообщил об ошибке «django.db.utils.OperationalError: нет такой таблицы: auth_permission», а именно:
(Django) [[email protected] teacher]# python manage.py migrate contenttypes
Operations to perform:
Apply all migrations: contenttypes
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: auth_permission
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 225, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/sql.py", line 280, in emit_post_migrate_signal
using=db)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 93, in create_permissions
"content_type", "codename"
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 162, in __iter__
self._fetch_all()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 1220, in iterator
for row in compiler.results_iter():
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 783, in results_iter
results = self.execute_sql(MULTI)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: auth_permission
Позже я проверил информацию и узнал, что такие таблицы, как django_content_type, auth_permission и т. Д., Были созданы по умолчанию. Сначала я подумал, что это проблема с моей версией Django, но когда я узнал из видео раньше, все работало нормально. Похоже, что моя предыдущая операция не прошла.
Продолжаю отладку, ввожу команду: python manage.py showmigrations, эта командаПоказываетDjangoВсе в проектеmigrationsФайлы и их статус,

[x]От имени завершенногоmigrationsФайл, []Указывает на файлы, которые не были выполнены или не были выполнены.
Оказывается, я не реализовал их для нашей конфигурации по умолчанию.migrations. Далее продолжаю выполнять команду:python manage.py migrate , На этот раз без названия приложения.

Хорошо, выполнение выполнено успешно, проверьте еще раз, выполните python manage.py showmigrations, все миграции выполнены.

Далее я определю, в порядке ли база данных, запрошу данные, и дисплей в порядке.

Hi. I made models.py by watching your video, but I’m not sure how to solve this problem.
First of all, when I access to 127.0.0.1:8000/admin/chat/chat/add,
It shows
django.db.utils.OperationalError: no such table: chat_contact
This is my models.py, and I migrated and deleted this models.py for several times.
from django.contrib.auth import get_user_model
from django.db import models
User = get_user_model()
# Create your models here.
class Contact(models.Model):
user = models.ForeignKey(User, related_name='friends', on_delete=models.CASCADE)
friends = models.ManyToManyField('self', blank=True)
def __str__(self):
return self.user.username
class Message(models.Model):
contact = models.ForeignKey(Contact, related_name='messages', on_delete=models.CASCADE)
content = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.contact.user.username
class Chat(models.Model):
participants = models.ManyToManyField(Contact, related_name='chats')
messages = models.ManyToManyField(Message, blank=True)
def last_10_messages(self):
return self.messages.objects.order_by('-timestamp').all()[:10]
def __str__(self):
return "{}".format(self.pk)
And this is the Error Occurs.
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/admin/chat/chat/add/Django Version: 3.0.4
Python Version: 3.6.5
Installed Applications:
[‘channels’,
‘chat’,
‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘django.contrib.sites’,
‘allauth’,
‘allauth.account’,
‘allauth.socialaccount’,
‘corsheaders’,
‘rest_auth’,
‘rest_auth.registration’,
‘rest_framework’,
‘rest_framework.authtoken’]
Installed Middleware:
[‘corsheaders.middleware.CorsMiddleware’,
‘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’]Template error:
In template E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangocontribadmintemplatesadminincludesfieldset.html, error at line 19
no such table: chat_contact
9 : {% for field in line %}
10 : <div{% if not line.fields|length_is:’1′ %} class=»fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}»{% elif field.is_checkbox %} class=»checkbox-row»{% endif %}>
11 : {% if not line.fields|length_is:’1′ and not field.is_readonly %}{{ field.errors }}{% endif %}
12 : {% if field.is_checkbox %}
13 : {{ field.field }}{{ field.label_tag }}
14 : {% else %}
15 : {{ field.label_tag }}
16 : {% if field.is_readonly %}
17 :{{ field.contents }}
18 : {% else %}
19 : {{ field.field }}
20 : {% endif %}
21 : {% endif %}
22 : {% if field.field.help_text %}
23 :{{ field.field.help_text|safe }}
24 : {% endif %}
25 :
26 : {% endfor %}
27 :
28 : {% endfor %}
29 :Traceback (most recent call last):
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 86, in _execute
return self.cursor.execute(sql, params)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendssqlite3base.py», line 396, in execute
return Database.Cursor.execute(self, query, params)The above exception (no such table: chat_contact) was the direct cause of the following exception:
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangocorehandlersexception.py», line 34, in inner
response = get_response(request)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangocorehandlersbase.py», line 145, in _get_response
response = self.process_exception_by_middleware(e, request)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangocorehandlersbase.py», line 143, in _get_response
response = response.render()
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateresponse.py», line 105, in render
self.content = self.rendered_content
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateresponse.py», line 83, in rendered_content
return template.render(context, self._request)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebackendsdjango.py», line 61, in render
return self.template.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 171, in render
return self._render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 163, in _render
return self.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateloader_tags.py», line 150, in render
return compiled_parent._render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 163, in _render
return self.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateloader_tags.py», line 150, in render
return compiled_parent._render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 163, in _render
return self.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateloader_tags.py», line 62, in render
result = block.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateloader_tags.py», line 62, in render
result = block.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatedefaulttags.py», line 209, in render
nodelist.append(node.render_annotated(context))
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplateloader_tags.py», line 188, in render
return template.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 173, in render
return self._render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 163, in _render
return self.nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatedefaulttags.py», line 209, in render
nodelist.append(node.render_annotated(context))
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatedefaulttags.py», line 209, in render
nodelist.append(node.render_annotated(context))
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatedefaulttags.py», line 309, in render
return nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatedefaulttags.py», line 309, in render
return nodelist.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 936, in render
bit = node.render_annotated(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 903, in render_annotated
return self.render(context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 992, in render
return render_value_in_context(output, context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangotemplatebase.py», line 971, in render_value_in_context
value = str(value)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoutilshtml.py», line 373, in
klass.str = lambda self: mark_safe(klass_str(self))
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformsboundfield.py», line 33, in str
return self.as_widget()
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformsboundfield.py», line 96, in as_widget
renderer=self.form.renderer,
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformswidgets.py», line 241, in render
context = self.get_context(name, value, attrs)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangocontribadminwidgets.py», line 288, in get_context
‘rendered_widget’: self.widget.render(name, value, attrs),
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformswidgets.py», line 241, in render
context = self.get_context(name, value, attrs)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformswidgets.py», line 678, in get_context
context = super().get_context(name, value, attrs)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformswidgets.py», line 639, in get_context
context[‘widget’][‘optgroups’] = self.optgroups(name, context[‘widget’][‘value’], attrs)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformswidgets.py», line 587, in optgroups
for index, (option_value, option_label) in enumerate(self.choices):
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangoformsmodels.py», line 1140, in iter
for obj in queryset:
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbmodelsquery.py», line 346, in _iterator
yield from self._iterable_class(self, chunked_fetch=use_chunked_fetch, chunk_size=chunk_size)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbmodelsquery.py», line 57, in iter
results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbmodelssqlcompiler.py», line 1151, in execute_sql
cursor.execute(sql, params)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 100, in execute
return super().execute(sql, params)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 86, in _execute
return self.cursor.execute(sql, params)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbutils.py», line 90, in exit
raise dj_exc_value.with_traceback(traceback) from exc_value
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendsutils.py», line 86, in _execute
return self.cursor.execute(sql, params)
File «E:DjangoDjango_ChannelsNew_Channelslibsite-packagesdjangodbbackendssqlite3base.py», line 396, in execute
return Database.Cursor.execute(self, query, params)Exception Type: OperationalError at /admin/chat/chat/add/
Exception Value: no such table: chat_contact

How should I solve this??
For a newly created project, the newly created app, when the database is migrated, executes the following two commands:
Python manage.py makemigrations teacher_app, the first step is successful
Python manage.py migrate teacher_app, the second step fails, error django.db.utils.OperationalError: no such table: django_content_type
Solution:
python manage.py makemigrations teacher_app
python manage.py migrate
the reason:
migrate,Be responsible forCorrectINSTALLED_APPSApplication inmigrate.makemigrations, responsible for creating a new migration based on your model modificationssqlmigrate, showing the migrated sql statementshowmigrations, which lists the migration of the project and its status.
Python manger.py makemigrations: will generate a migrations folder in the current directory, the contents of the folder is the contents of the database to be executed, will generate sql statement, you can use python manger.py sqlmigrate app 0001 to view the specific sql statement.
Python manager.py migrate: Execute the generated migrations file, apply the action to the database file, and generate the table.
Python manage.py migrate app_name: Only execute the migrations file under the app_name application, generate the corresponding table, and do not execute the other migrations files. But after creating a new project, we will automatically generate some migrations files for us. Only after these default migrations files are executed, the default provided tables (such as django_content_type, auth_permission, etc.) can be executed to execute our own migrations. File, generate the table we want.
The problem is solved by a specific process.
My environment: Centos6.8+anaconda+pycharm+python3.7+Django1.8
This is my project building process:
1. Establish a project
(Django) [[email protected] Django]# django-admin startproject teacher
(Django) [[email protected] Django]# cd teacher
(Django) [[email protected] teacher]# python manage.py startapp teacher_app
2. Write the class in the models.py file of teacher_app
from django.db import models
# Create your models here.
class Teacher(models.Model):
name = models.CharField(max_length=20)
age = models.IntegerField()
address = models.CharField(max_length=20)
email = models.CharField(max_length=20)
def __str__(self):
return self.name
3. Add app to setting
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'teacher_app',
)
4. Perform database migration:
(Django) [[email protected] teacher]# python manage.py makemigrations teacher_app
Migrations for ‘teacher_app’:
0001_initial.py:
— Create model Teacher
(Django) [[email protected] teacher]# python manage.py migrate teacher_app
The second step failed. Error message: Django.db.utils.OperationalError: no such table: django_content_type,
«Error creating new content types. Please make sure contenttypes «
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.
Specific error message:
(Django) [[email protected] teacher]# python manage.py makemigrations teacher_app
Migrations for 'teacher_app':
0001_initial.py:
- Create model Teacher
(Django) [[email protected] teacher]# python manage.py migrate teacher_app
Operations to perform:
Apply all migrations: teacher_app
Running migrations:
Rendering model states... DONE
Applying teacher_app.0001_initial... OK
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: django_content_type
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 65, in get_for_model
ct = self.get(app_label=opts.app_label, model=opts.model_name)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/manager.py", line 127, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 328, in get
num = len(clone)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 144, in __len__
self._fetch_all()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 238, in iterator
results = compiler.execute_sql()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: django_content_type
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 225, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/sql.py", line 280, in emit_post_migrate_signal
using=db)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 82, in create_permissions
ctype = ContentType.objects.db_manager(using).get_for_model(klass)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/contenttypes/models.py", line 78, in get_for_model
"Error creating new content types. Please make sure contenttypes "
RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually.
The error message tells me that when doing database migration, make sure that the contenttypes are migrated. Then I started to migrate the contenttypes, but I still get an error. The error is «django.db.utils.OperationalError: no such table: auth_permission», as follows:
(Django) [[email protected] teacher]# python manage.py migrate contenttypes
Operations to perform:
Apply all migrations: contenttypes
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Traceback (most recent call last):
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
sqlite3.OperationalError: no such table: auth_permission
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "manage.py", line 10, in <module>
execute_from_command_line(sys.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
utility.execute()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/__init__.py", line 330, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 390, in run_from_argv
self.execute(*args, **cmd_options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/base.py", line 441, in execute
output = self.handle(*args, **options)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 225, in handle
emit_post_migrate_signal(created_models, self.verbosity, self.interactive, connection.alias)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/core/management/sql.py", line 280, in emit_post_migrate_signal
using=db)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/dispatch/dispatcher.py", line 201, in send
response = receiver(signal=self, sender=sender, **named)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/contrib/auth/management/__init__.py", line 93, in create_permissions
"content_type", "codename"
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 162, in __iter__
self._fetch_all()
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 965, in _fetch_all
self._result_cache = list(self.iterator())
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/query.py", line 1220, in iterator
for row in compiler.results_iter():
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 783, in results_iter
results = self.execute_sql(MULTI)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 829, in execute_sql
cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/utils.py", line 97, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/utils/six.py", line 658, in reraise
raise value.with_traceback(tb)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "/root/anaconda3/envs/Django/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py", line 318, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: auth_permission
Later, I checked the information and learned that tables like django_content_type and auth_permission were created by default. I thought it was my Django version at first, but when I was learning the video, it was fine. It seems that my previous operation was not in place.
I continue to debug, enter the command: python manage.py showmigrations, this command isShowsDjangoAll in the projectmigrationsFile and its status,

[x]The representative has already completedmigrationsDocument,[]Indicates a file that has not been executed or failed to execute.
It turned out that I did not implement these for our default configuration.migrations. Next I continue to execute the command:python manage.py migrate This time, the application name was not taken.

Yes, the execution is successful, check again, execute python manage.py showmigrations, all the migrations are executed.

I will further determine whether the database is good or not, query the data, and display no problem.

При выполнении manage.py makemigrations появляется ошибка о том, что таблица (на которую надо сделать миграцию) не существует:
Список вызовов
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagement__init__.py", line 367, in execute_from_command_line
utility.execute()
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagement__init__.py", line 359, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 294, in run_from_argv
self.execute(*args, **cmd_options)
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 342, in execute
self.check()
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 374, in check
include_deployment_checks=include_deployment_checks,
File "D:enviropmentsNewElionlibsite-packagesdjangocoremanagementbase.py", line 361, in _run_checks
return checks.run_checks(**kwargs)
File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksregistry.py", line 81, in run_checks
new_errors = check(app_configs=app_configs)
File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksurls.py", line 14, in check_url_config
return check_resolver(resolver)
File "D:enviropmentsNewElionlibsite-packagesdjangocorechecksurls.py", line 24, in check_resolver
for pattern in resolver.url_patterns:
File "D:enviropmentsNewElionlibsite-packagesdjangoutilsfunctional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:enviropmentsNewElionlibsite-packagesdjangourlsresolvers.py", line 313, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "D:enviropmentsNewElionlibsite-packagesdjangoutilsfunctional.py", line 35, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "D:enviropmentsNewElionlibsite-packagesdjangourlsresolvers.py", line 306, in urlconf_module
return import_module(self.urlconf_name)
File "D:Python27Libimportlib__init__.py", line 37, in import_module
__import__(name)
File "D:YandexDiskWORK!Projects DjangotestElionElionurls.py", line 5, in <module>
from about import views as about_views
File "D:YandexDiskWORK!Projects DjangotestElionaboutviews.py", line 6, in <module>
from .forms import ContactMessageForm, SubmitApplication
File "D:YandexDiskWORK!Projects DjangotestElionaboutforms.py", line 42, in <module>
class SubmitApplication(forms.Form):
File "D:YandexDiskWORK!Projects DjangotestElionaboutforms.py", line 43, in SubmitApplication
regions = [(obj.id, obj.region) for obj in AreasWork.objects.all()]
File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 256, in __iter__
self._fetch_all()
File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 1087, in _fetch_all
self._result_cache = list(self.iterator())
File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelsquery.py", line 54, in __iter__
results = compiler.execute_sql()
File "D:enviropmentsNewElionlibsite-packagesdjangodbmodelssqlcompiler.py", line 835, in execute_sql
cursor.execute(sql, params)
File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 79, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "D:enviropmentsNewElionlibsite-packagesdjangodbutils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendsutils.py", line 64, in execute
return self.cursor.execute(sql, params)
File "D:enviropmentsNewElionlibsite-packagesdjangodbbackendssqlite3base.py", line 337, in execute
return Database.Cursor.execute(self, query, params)
django.db.utils.OperationalError: no such table: AreasWork
В этом списке вызовов показано, что вызывается forms.py этого приложения в том месте где есть обращение к данной таблице:
# Elionaboutforms.py:
class SubmitApplication(forms.Form):
regions = [(obj.id, obj.region) for obj in AreasWork.objects.all()] # Ошибка в этой строке
choice_region = [(None, 'Выберите город')] + regions + [('0', 'Другой')]
region = forms.ChoiceField(label='Область', choices=choice_region,
widget=forms.Select(attrs={'class': 'form-control'}))
............
Если в этом месте убрать обращение к БД, то ошибок больше никаких не появляется. Даже после выполнения manage.py migrate и в forms.py вернуть код обратно, то всё будет работать нормально, без ошибок.
Также, я нашёл, что у кого-то была аналогичная проблема и тоже ошибка в файле forms.py при обращении к БД.
Понятно, что для решения проблемы, надо тупо убрать обращение к БД в форме, но мне интересно, почему вообще такое происходит и что я делаю не правильно?
My Code:
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0066_collection_management_permissions'),
('wagtailforms', '0004_add_verbose_name_plural'),
('wagtailredirects', '0006_redirect_increase_max_length'),
('home', '0017_alter_orderdetailpage_options'),
]
operations = [
# migrations.RemoveField(
# # model_name='orderdetailpage',
# name='page_ptr',
# ),
# migrations.RemoveField(
# # model_name='successpage',
# name='page_ptr',
# ),
migrations.DeleteModel(
name='MerchantHomePage',
),
migrations.DeleteModel(
name='OrderDetailPage',
),
migrations.DeleteModel(
name='SuccessPage',
),
]
Error:
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: near ")": syntax error
Solution:
- It occurs because you are trying to Delete a Class that has no Fields.
- Get rid of the RemoveField section in your migration: normally such migrations have auto in their names eg
0021_auto_20211126_0955.py
Example in my case
- Changed From:
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0066_collection_management_permissions'),
('wagtailredirects', '0006_redirect_increase_max_length'),
('wagtailforms', '0004_add_verbose_name_plural'),
('home', '0020_auto_20211126_0945'),
]
operations = [
migrations.RemoveField(
model_name='orderdetailpage',
name='page_ptr',
),
migrations.DeleteModel(
name='MerchantHomePage',
),
migrations.DeleteModel(
name='OrderDetailPage',
),
]
- to:
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wagtailcore', '0066_collection_management_permissions'),
('wagtailredirects', '0006_redirect_increase_max_length'),
('wagtailforms', '0004_add_verbose_name_plural'),
('home', '0020_auto_20211126_0945'),
]
operations = [
# ..removed the RemoveField section
migrations.DeleteModel(
name='MerchantHomePage',
),
migrations.DeleteModel(
name='OrderDetailPage',
),
]
- Then run
python manage.py migrateagain and everything should be good
Solution 1:[1]
As you went through the tutorial you must have come across the section on migration, as this was one of the major changes in Django 1.7
Prior to Django 1.7, the syncdb command never made any change that had a chance to destroy data currently in the database. This meant that if you did syncdb for a model, then added a new row to the model (a new column, effectively), syncdb would not affect that change in the database.
So either you dropped that table by hand and then ran syncdb again (to recreate it from scratch, losing any data), or you manually entered the correct statements at the database to add only that column.
Then a project came along called south which implemented migrations. This meant that there was a way to migrate forward (and reverse, undo) any changes to the database and preserve the integrity of data.
In Django 1.7, the functionality of south was integrated directly into Django. When working with migrations, the process is a bit different.
- Make changes to
models.py(as normal). - Create a migration. This generates code to go from the current state to the next state of your model. This is done with the
makemigrationscommand. This command is smart enough to detect what has changed and will create a script to effect that change to your database. - Next, you apply that migration with
migrate. This command applies all migrations in order.
So your normal syncdb is now a two-step process, python manage.py makemigrations followed by python manage.py migrate.
Now, on to your specific problem:
class Snippet(models.Model):
owner = models.ForeignKey('auth.User', related_name='snippets')
highlighted = models.TextField()
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
In this model, you have two fields highlighted and code that is required (they cannot be null).
Had you added these fields from the start, there wouldn’t be a problem because the table has no existing rows?
However, if the table has already been created and you add a field that cannot be null, you have to define a default value to provide for any existing rows — otherwise, the database will not accept your changes because they would violate the data integrity constraints.
This is what the command is prompting you about. You can tell Django to apply a default during migration, or you can give it a «blank» default highlighted = models.TextField(default='') in the model itself.
Solution 2:[2]
Let’s focus on the error:
Exception Value:
no such column: snippets_snippet.owner_id
Let’s see if that’s true…
You can use the manage.py command to access your db shell (this will use the settings.py variables, so you’re sure to connect to the right one).
manage.py dbshell
You can now show the details of your table by typing:
.schema TABLE_NAME
Or in your case:
.schema snippets_snippet
More sqlite commands can be found here or by issuing a:
.help
Lastly, end your session by typing:
.quit
This doesn’t get you out of the woods, but it helps you know what end of the problem to work on 
Good luck!
Solution 3:[3]
Step 1: Delete the db.sqlite3 file.
Step 2 : $ python manage.py migrate
Step 3 : $ python manage.py makemigrations
Step 4: Create the super user using $ python manage.py createsuperuser
new db.sqlite3 will generates automatically
Solution 4:[4]
I see we have the same problem here, I have the same error. I want to write this for the future user who will experience the same error.
After making changes to your class Snippet model like @Burhan Khalid said, you must migrate tables:
python manage.py makemigrations snippets
python manage.py migrate
And that should resolve the error.
Enjoy.
Solution 5:[5]
This error can happen if you instantiate a class that relies on that table, for example in views.py.
Solution 6:[6]
Initially ,I have commented my new fields which is causing those errors, and run python manage.py makemigrations and then python manage.py migrate to actually delete those new fields.
class FootballScore(models.Model):
team = models.ForeignKey(Team, related_name='teams_football', on_delete=models.CASCADE)
# match_played = models.IntegerField(default='0')
# lose = models.IntegerField(default='0')
win = models.IntegerField(default='0')
# points = models.IntegerField(default='0')
class FootballScore(models.Model):
team = models.ForeignKey(Team, related_name='teams_football', on_delete=models.CASCADE)
match_played = models.IntegerField(default='0')
lose = models.IntegerField(default='0')
win = models.IntegerField(default='0')
points = models.IntegerField(default='0')
Then i freshly uncommented them and run python manage.py makemigrations and python manage.py migrate and boom. It worked for me. 
Solution 7:[7]
I faced this problem and this is how I solved it.
1) Delete all the migration records from your app’s migration directory. These are files named 0001_,0002_,0003_ etc. Be careful as to not delete the
_init__.py file.
2) Delete the db.sqlite3 file. It will be regenerated later.
Now, run the following commands:
python manage.py makemigrations appname
python manage.py migrate
Be sure to write the name of your app after makemigrations. You might have to create a superuser to access your database again. Do so by the following
python manage.py createsuperuser
Solution 8:[8]
The most direct way of solving this type of problem is just the following 3 steps process:
-
Delete all the migration related files from app’s migrations folder/directory (these basically starts with
0001,0002,0003etc). -
Delete/Rename the existing database file named db.sqlite3 from App directory.
-
Now run the following command:
python manage.py migrateFinally execute
python manage.py createsuperuserto perform the administrative tasks (If you want).
Solution 9:[9]
I did the following
- Delete my db.sqlite3 database
python manage.py makemigrationspython manage.py migrate
It renewed the database and fixed the issues without affecting my project. Please note you might need to do python manage.py createsuperuser because it will affect all your objects being created.
Solution 10:[10]
You did every thing correct, I have been gone through same problem.
First delete you db and migrations
I solved my adding name of my app in makemigrations:
python manage.py makemigrations appname
python manage.py migrate
This will definitely work.
Solution 11:[11]
1.First delete only 0001_initial.py from migration file
2.Delete dbsqulite file
3.python manage.py makemigrations appname
4.python manage.py migrate
finally solved
Solution 12:[12]
Taken from Burhan Khalid’s answer and his comment about migrations: what worked for me was removing the content of the «migrations» folder along with the database, and then running manage.py migrate. Removing the database is not enough because of the saved information about table structure in the migrations folder.
Solution 13:[13]
Agree with Rishikesh. I too tried to solve this issue for a long time. This will be solved with either or both of 2 methods-
1.Try deleting the migrations in the app’s migrations folder(except init.py)
and then running makemigrations command
2.If that doesn’t work, try renaming the model (this is the last resort and might get a little messy but will work for sure.If django asks «did you rename the model? just press N.»).Hope it helps..:)
Solution 14:[14]
You did not migrated all changes you made in model. so
1) python manage.py makemigrations
2) python manage.py migrate
3) python manag.py runserver
it works 100%
Solution 15:[15]
This may be one of the most annoying and time-consuming issue, the traceback is not helpful for solving the problem.
This means your database is messed up, which you must delete the database to start again.
It is worth-mentioning to restruct some existing field:
- When we tries to connect models, there are basically two ways:
first one
from comments.models import Comment
class Article(models.Model):
comments = models.ManyToManyField(Comment)
second one
class Article(models.Model):
comments = models.ManyToManyField('comments.Comment')
The first method, widely used by beginners and it may cause circular import issue, which occurs when you tries to import A.py in B.py and in B.py it also imports A.py.
Therefore, we must abandon the first approach, and implement the second to all. Here’s the way to solve the problem, unfortunately you need to delete the database.
- delete
db.sqlite3 - for all apps, open
migrationfolder, delete all except for__init__.py python manage.py makemigrationspython manage.py migrate
One the problem is solved, if you follow the convention, the issue will never occur again:
- Do not import models wherever you are, always use this instead:
from django.apps import apps
apps.get_model(app_name, model_name)
# Article = apps.get_model('articles', 'Article')
in fields it can be briefed to string, which <app_name>_<model_name>
class Article(models.Model):
comments = models.ManyToManyField('comments.Comment')
here is a script to delete all migrations, create a file clean.py at the same level to manage.py
import os
def recursor(dirpath):
# print(dirpath)
delfiles = []
deldirs = []
with os.scandir(dirpath) as l1:
for e1 in l1:
if not e1.is_file():
with os.scandir(e1.path) as l2:
for e2 in l2:
if e2.name == 'migrations':
with os.scandir(e2.path) as l3:
for e3 in l3:
if not e3.name == '__init__.py':
print(e3.path)
if e3.is_file():
delfiles.append(e3.path)
else:
deldirs.append(e3.path)
with os.scandir(e3.path) as l4:
for e4 in l4:
delfiles.append(e4)
yn = input('are you sure to delete all the files above?(y/n)')
if yn == 'y':
for dp in delfiles:
os.remove(dp)
for dp in deldirs:
os.rmdir(dp)
recursor(os.path.dirname(os.path.realpath(__file__)))
Solution 16:[16]
If your issue is like mine, then this a workaround.
The good news is that you wont have to delete your db.
Check that there isn’t some other model that uses this model as a reference.
django.db.utils.OperationalError: no such column: parts_part_type.blah
This was only happening to me because I had another model called «product» in a different app called «products» that referenced this model.
part = models.ForeignKey("parts.Part", related_name="some part", limit_choices_to={'part_type':Part_Type.objects.get(prefix='PART')},)
My solution was:
- comment out the other app (in this case prodcuts) from settings.py
python manage.py makemigrations; python manage.py migrate- un-comment the other app so its enabled again.
python manage.py makemigrations; python manage.py migrate
Technically I think I need to change the limit_choices_to reference so
Solution 17:[17]
I had this problem recently, even though on a different tutorial. I had the django version 2.2.3 so I thought I should not have this kind of issue.
In my case, once I add a new field to a model and try to access it in admin, it would say no such column.
I learnt the ‘right’ way after three days of searching for solution with nothing working.
First, if you are making a change to a model, you should make sure that the server is not running. This is what caused my own problem.
And this is not easy to rectify. I had to rename the field (while server was not running) and re-apply migrations.
Second, I found that python manage.py makemigrations <app_name> captured the change as opposed to just python manage.py makemigrations. I don’t know why.
You could also follow that up with python manage.py migrate <app_name>. I’m glad I found this out by myself.
Solution 18:[18]
just remember there is a pycache folder hidden inside the migrations folder so if you change your models and delete all your migration files you MUST delete the pycache folder also.
The only one you should not delete is your init file.
Hope this helps
Solution 19:[19]
In my case, in admin.py I was querying from the table in which new ForeignKey field was added. So comment out admin.py then run makemigrations and migrate command as usual. Finally uncomment admin.py.
Solution 20:[20]
If the error persists after doing what @Burhan Khalid said
Try this line: python manage.py migrate —run-syncdb
Solution 21:[21]
Anyone coming here:
Remove all migrations
Remove db.sqlite file
redo migrations
Solution 22:[22]
I simple made a careless mistake of forgetting to actually apply the migration (migrate) after making migrations. Writing this just in case anyone might make the same mistake.
Solution 23:[23]
I think you skipped this steps…run the following commands to see if you had forgotten to execute them…it worked for me.
$ python manage.py makemigrations
$ python manage.py migrate
Thank you.
Solution 24:[24]
Deleting all your migrations in the migration folder of your django app, then run makemigrations followed by migrate commands. You should be able to get out of the woods.
Solution 25:[25]
I had same issue with sqlite. My models.py looked all right. I did the following:
sqlite3 db.sqlite3
.tables
PRAGMA table_info(table_name);
Thru PRAGMA I was able to see that there was columns missing in the table failing.
I dropped all tables in the app. Be careful because this will make lose your data in the tables.
DROP table table_name
.quit
Then do this:
python manage.py makemigrations your_app
python manage.py migrate your_app
python manage.py sqlmigrate your_app 0001
Then enter again to sqlite as follows and paste all the code you got from sqlimigrate:
sqlite3 db.sqlite3
As an example, this is what I pasted inside sqlite:
CREATE TABLE "adpet_ad" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "title" varchar(200) NOT NULL, "breed" varchar(30) NULL, "weight" decimal NULL, "age" integer NULL, "text" text NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL, "picture" BLOB NULL, "content_type" varchar(256) NULL, "name" varchar(100) NULL, "phone" varchar(31) NOT NULL, "gender_id" integer NULL REFERENCES "adpet_gender" ("id") DEFERRABLE INITIALLY DEFERRED, "owner_id" integer NOT NULL REFERENCES "auth_user" ("id") DEFERRABLE INITIALLY DEFERRED, "size_id" integer NULL REFERENCES "adpet_size" ("id") DEFERRABLE INITIALLY DEFERRED, "specie_id" integer NULL REFERENCES "adpet_specie" ("id") DEFERRABLE INITIALLY DEFERRED, "sterilized_id" integer NULL REFERENCES "adpet_sterilized" ("id") DEFERRABLE INITIALLY DEFERRED, "vaccinated_id" integer NULL REFERENCES "adpet_vaccinated" ("id") DEFERRABLE INITIALLY DEFERRED);
Solution 26:[26]
Instead of deleting any existing migrations as some have said, do this:
python manage.py migrate --fake #(only if the below commands don't work)
python manage.py migrate --run-syncdb
python manage.py runserver makemigrations
python manage.py runserver
Solution 27:[27]
I add this because, if your problem persists, it might be that you are attempting to access the database in the init function of a class. The makemigrations process checks all of your modules and classes, and if you attempt to access a table in the database in the init function it might raise an error. Comment that line out and then try makemigrations and migrate
Solution 28:[28]
Whenever you add a new fields you need to change in your database too so you need to run some commands to add a new column
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
If it’s still not working delete your migrations files that name starts with 00 something similar and run those same commands from above. If it’s still not working. delete SQLite database from your project and run those commands once again
Solution 29:[29]
Well, I cannot speak particularly to the db aspect of the issue, or the answers…And I tried deleting the 0001_initial.py but the error persisted.
So for of you(us) experiencing the «no such column: snippets_snippet.owner_id» type of error with django (not necessarily REST), the issue is from the foreign key variable, it’s expecting a default value which isn’t specified.
Solution: add default='' to the foreign key arguments, and it you’ll be fine. For context to this person’s code; owner = models.ForeignKey('auth.User', related_name='snippets', default='')
Solution 30:[30]
I am also faced same problem.
If you’re adding a new field then it gives the error as no column found.
Then you apply make migration command and after that migrate command
Then still same error..
EX…
path=models.FilePathField()
Add default value for field
path=models.FilePathField(default='')
and than apply command
python manage.py makemigrations
python manage.py migrate
It may help you
