Меню

Ошибка django db utils operationalerror

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, Показать перенесенный оператор sql
  • showmigrations, В котором перечислены миграция и статус проекта.

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

image

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 modifications
  • sqlmigrate, showing the migrated sql statement
  • showmigrations, 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.

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка direct3d device was lost and cannot be reset due to internal error
  • Ошибка distributedcom код события 10016 windows