OperationalError:没有这样的表:django_content_type 和 django_session

问题描述

我无法访问我的应用程序,当我输入 URL 时,它给了我错误

OperationalError: no such table: django_session

这通常意味着我需要迁移或删除我的 sqlite 数据库并重做迁移,所以我做了多次。我删除了迁移文件夹和 sqlite3.db 中的所有内容并运行:

python manage.py makemigrations app_name
python manage.py migrate app_name

尚无错误。然后在创建超级用户后我运行:

python manage.py runserver

它告诉我尚未进行 18 次迁移,我可以通过以下方式进行修复:

python manage.py migrate --fake

我尝试了该站点,但我再次得到没有这样的表:django_session 错误

我读了这个帖子 Django: no such table: django_session 并尝试了其中的所有内容包括批准的解决方案,同样的错误

此外,当我再次尝试运行 migrate 命令时,出现此错误

OperationalError: no such table: django_content_type

所以我去了这个线程 sqlite3.OperationalError: no such table: django_content_type

再一次,对他们有用的解决方案对我不起作用。

这个问题是在我们迁移到 MysqL 后开始的,我尝试使用 .env 文件切换数据库,但遇到了这些问题,所以我尝试切换回 sqlite 以便我至少可以在项目上工作。团队正在迁移到 MysqL,我们有人成功地使用这两个数据库,所以这应该不是数据库问题。

这是我的 settings.py 文件

import os
from pathlib import Path
from django.contrib.messages import constants as message_constants

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

SECRET_KEY = os.environ.get("DJ_SECRET_KEY",default="Testing")
DEBUG = os.environ.get("DJ_DEBUG",default=True)
ALLOWED_HOSTS = ["redonkulator.apps.dev.mach9.usmc.mil","localhost","127.0.0.1"]

# Application deFinition

INSTALLED_APPS = [
    "django.contrib.admin","django.contrib.auth","django.contrib.contenttypes","django.contrib.sessions","django.contrib.messages","django.contrib.staticfiles","redonkulator_app.apps.RedonkulatorAppConfig","jquery","debug_toolbar",]

MIDDLEWARE = [
    "django.middleware.security.SecurityMiddleware","django.contrib.sessions.middleware.SessionMiddleware","django.contrib.auth.middleware.AuthenticationMiddleware","django.middleware.common.CommonMiddleware","debug_toolbar.middleware.DebugToolbarMiddleware","django.middleware.csrf.CsrfViewMiddleware","django.contrib.messages.middleware.MessageMiddleware","django.middleware.clickjacking.XFrameOptionsMiddleware",]

ROOT_URLconf = "iiimef_project.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates","Dirs": ["templates"],"APP_Dirs": True,"OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug","django.template.context_processors.request","django.contrib.auth.context_processors.auth","django.contrib.messages.context_processors.messages",],},]

AUTH_USER_MODEL = "redonkulator_app.MlptUsers"

Wsgi_APPLICATION = "iiimef_project.wsgi.application"

# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": os.environ.get("sql_ENGINE","django.db.backends.sqlite3"),"NAME": os.environ.get(
            "sql_DATABASE",os.path.join(BASE_DIR,"db.sqlite3"),),"USER": os.environ.get("sql_USER","user"),"PASSWORD": os.environ.get("sql_PASSWORD","password"),"HOST": os.environ.get("sql_HOST","localhost"),"PORT": os.environ.get("sql_PORT","5432"),}
}

# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",{
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",{
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",{
        "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",]

# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS,JavaScript,Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = "/static/"
STATIC_ROOT = os.path.join(BASE_DIR,"static")

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

LOGIN_REDIRECT_URL = ""
logoUT_REDIRECT_URL = "/about"
LOGIN_URL = "/login"

MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"

# needed to overwrite bootsrap classes
MESSAGE_TAGS = {
    message_constants.DEBUG: "debug",message_constants.INFO: "info",message_constants.SUCCESS: "success",message_constants.WARNING: "warning",message_constants.ERROR: "danger",}


INTERNAL_IPS = [
    "127.0.0.1",]

我安装的应用程序中有 session 和 contenttype,中间件中有 session,这里有什么明显错误的地方吗?

这是我的 .env

DJ_SECRET_KEY=super-secret-key
DJ_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] 0.0.0.0 *
DJ_DEBUG=True
sql_DATABASE=redonkulator
sql_ENGINE=django.db.backends.MysqL
sql_USER=[myusername]
sql_PASSWORD=[mypassword]
sql_HOST=localhost
sql_PORT=3306

我知道这个 .env 不适用于我的设置,这没关系,因为我现在只是想让 sqlite 工作。

还有一件事,从今天开始,在这个问题开始后不久,每个 django 导入都用黄色下划线标出。例如,settings.py 中的“django.contrib.messages”带有下划线,但是我没有收到模块导入错误,所以我认为这不是问题。

最后,这里是 content_type 错误的回溯:

Traceback (most recent call last):
  File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py",line 22,in <module>
    main()
  File "C:\Users\dwill\Documents\GitHub\MLPT\manage.py",line 18,in main
    execute_from_command_line(sys.argv)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py",line 419,in execute_from_command_line
    utility.execute()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\__init__.py",line 413,in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py",line 354,in run_from_argv
    self.execute(*args,**cmd_options)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py",line 398,in execute
    output = self.handle(*args,**options)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\base.py",line 89,in wrapped
    res = handle_func(*args,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\commands\migrate.py",line 268,in handle
    emit_post_migrate_signal(
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\management\sql.py",line 42,in emit_post_migrate_signal
    models.signals.post_migrate.send(
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py",line 180,in send
    return [
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\dispatch\dispatcher.py",line 181,in <listcomp>
    (receiver,receiver(signal=self,sender=sender,**named))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\management\__init__.py",in create_permissions
    create_contenttypes(app_config,verbosity=verbosity,interactive=interactive,using=using,apps=apps,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py",line 119,in create_contenttypes
    content_types,app_models = get_contenttypes_and_models(app_config,using,ContentType)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\contenttypes\management\__init__.py",line 94,in get_contenttypes_and_models   
    content_types = {
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py",line 280,in __iter__
    self._fetch_all()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py",line 1324,in _fetch_all
    self._result_cache = list(self._iterable_class(self))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py",line 51,in __iter__
    results = compiler.execute_sql(chunked_fetch=self.chunked_fetch,chunk_size=self.chunk_size)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py",line 1175,in execute_sql
    cursor.execute(sql,params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py",line 98,in execute
    return super().execute(sql,line 66,in execute
    return self._execute_with_wrappers(sql,params,many=False,executor=self._execute)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py",line 75,in _execute_with_wrappers
    return executor(sql,many,context)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py",line 84,in _execute
    return self.cursor.execute(sql,params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\utils.py",line 90,in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py",params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\sqlite3\base.py",line 423,in execute
    return Database.Cursor.execute(self,query,params)
django.db.utils.OperationalError: no such table: django_content_type

和 django 会话错误

Traceback (most recent call last):
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py",params)

The above exception (no such table: django_session) was the direct cause of the following exception:
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\exception.py",line 47,in inner
    response = get_response(request)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\core\handlers\base.py",in _get_response
    response = wrapped_callback(request,*callback_args,**callback_kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py",line 44,in _wrapped_view_func
    response = view_func(request,*args,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\admin\sites.py",line 414,in login
    return LoginView.as_view(**defaults)(request)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py",line 70,in view
    return self.dispatch(request,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\utils\decorators.py",line 43,in _wrapper
    return bound_method(*args,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\debug.py",in sensitive_post_parameters_wrapper
    return view(request,line 130,in _wrapped_view
    response = view_func(request,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\decorators\cache.py",**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py",line 63,in dispatch
    return super().dispatch(request,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py",in dispatch
    return handler(request,**kwargs)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\edit.py",line 142,in post
    return self.form_valid(form)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\views.py",line 92,in form_valid
    auth_login(self.request,form.get_user())
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\auth\__init__.py",line 111,in login
    request.session.cycle_key()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py",line 344,in cycle_key
    self.create()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py",in create
    self._session_key = self._get_new_session_key()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\base.py",line 196,in _get_new_session_key
    if not self.exists(session_key):
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\contrib\sessions\backends\db.py",in exists
    return self.model.objects.filter(session_key=session_key).exists()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\query.py",line 808,in exists
    return self.query.has_results(using=self.db)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\query.py",line 550,in has_results
    return compiler.has_results()
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py",line 1145,in has_results
    return bool(self.execute_sql(SINGLE))
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\models\sql\compiler.py",params)
  File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py",line 198,in execute
    return self._record(self.cursor.execute,sql,line 133,in _record
    return method(sql,params)

Exception Type: OperationalError at /admin/login/
Exception Value: no such table: django_session

解决方法

进行迁移后,尝试同步您的数据库:

python manage.py migrate --run-syncdb

它已经为我解决了几次这个错误代码。

,

尽量避免使用 .env 文件以排除这种情况。

更新settings.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql','NAME': 'DBNAME','USER': 'USER','PASSWORD': 'PASS','HOST': '127.0.0.1','PORT': 3306
    }
}

如果这可行,那么我们已经找到了问题的根源,应该仔细检查 .env 文件的位置并从那里向后工作。