OperationalError:没有这样的表:django_content_type 和 django_session
Posted
技术标签:
【中文标题】OperationalError:没有这样的表:django_content_type 和 django_session【英文标题】:OperationalError: no such table: django_content_type and django_session 【发布时间】:2021-09-02 04:40:36 【问题描述】:我无法访问我的应用程序,当我输入 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
我尝试了该站点,但再次得到 no such table: 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",
"django.contrib.messages.middleware.MessageMiddleware",
]
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",
]
我在已安装的应用程序和中间件中的会话中有会话和内容类型,这里有什么看起来明显错误的东西吗?
这是我的 .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", line 42, 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, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", 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, params, 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", line 84, in _execute
return self.cursor.execute(sql, 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", line 84, in _execute
return self.cursor.execute(sql, 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)
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", line 181, 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, *args, **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", line 89, in sensitive_post_parameters_wrapper
return view(request, *args, **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\utils\decorators.py", line 130, in _wrapped_view
response = view_func(request, *args, **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\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\auth\views.py", line 63, in dispatch
return super().dispatch(request, *args, **kwargs)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\views\generic\base.py", line 98, in dispatch
return handler(request, *args, **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", line 51, 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", line 47, 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", line 1175, in execute_sql
cursor.execute(sql, 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, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\debug_toolbar\panels\sql\tracking.py", line 133, in _record
return method(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, params)
File "C:\Users\dwill\Documents\GitHub\MLPT\myenv\lib\site-packages\django\db\backends\utils.py", 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, params, 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", line 84, in _execute
return self.cursor.execute(sql, 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)
Exception Type: OperationalError at /admin/login/
Exception Value: no such table: django_session
【问题讨论】:
是的,这是我尝试的第一件事 【参考方案1】:尝试避免使用 .env
文件以排除这种情况。
更新settings.py
DATABASES =
'default':
'ENGINE': 'django.db.backends.mysql',
'NAME': 'DBNAME',
'USER': 'USER',
'PASSWORD': 'PASS',
'HOST': '127.0.0.1',
'PORT': 3306
如果这可行,那么我们已经找到了问题的根源,应该仔细检查.env
文件的位置,然后从那里向后工作。
【讨论】:
这是一个弃用的命令,已经被migrate替换了,但是我已经尝试过了。 您已经成功连接到您的新数据库了吗? 我没有,但我现在可以让 sqlite 正常工作,因为生产服务器已经在运行 mysql。我使用 mysql 的主要目的是确保测试正常工作,因为两个数据库使用 id 做不同的事情。 如果你知道如何让 mysql 运行,那就太好了。 mysql 服务器当前正在我的本地主机上运行,当我尝试连接到它时,我得到“S01Got packet out of order” 尝试先不使用.env
文件连接到您的数据库。 DATABASES = 'default': 'ENGINE': 'django.db.backends.mysql', 'NAME': 'DBNAME', 'USER': 'ROOT', 'PASSWORD': 'PASS', 'HOST': '127.0.0.1', 'PORT': 3306
【参考方案2】:
进行迁移后,尝试同步您的数据库:
python manage.py migrate --run-syncdb
它已经多次为我解决了这个错误代码。
【讨论】:
以上是关于OperationalError:没有这样的表:django_content_type 和 django_session的主要内容,如果未能解决你的问题,请参考以下文章
django:sqlite3.OperationalError:没有这样的表
Django / sqlite3“OperationalError:没有这样的表”关于线程操作
OperationalError:没有这样的表:django_content_type 和 django_session
Graphite Web 错误日志,OperationalError:没有这样的表:auth_user
/admin/login/ 的 OperationalError 没有这样的表:auth_user
/admin/registration/donor/ 处的 OperationalError 没有这样的表:registration_donor