首次部署Django项目至Heroku遇django_content_type表不存在错误
Django部署Heroku时
django_content_type表不存在的问题 问题描述
首次将Django项目部署到Heroku,执行以下操作时出现异常:
- 用户注册/登录功能无法正常使用
- 执行
heroku run python manage.py makemigrations失败 - 执行
heroku run python manage.py migrate(含--fake参数)报错
错误信息
Traceback (most recent call last): File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co... ^ The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 268, in handle emit_post_migrate_signal( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/sql.py", line 42, in emit_post_migrate_signal models.signals.post_migrate.send( File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 180, in send return [ File "/app/.heroku/python/lib/python3.10/site-packages/django/dispatch/dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/app/.heroku/python/lib/python3.10/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 "/app/.heroku/python/lib/python3.10/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 "/app/.heroku/python/lib/python3.10/site-packages/django/contrib/contenttypes/management/__init__.py", line 94, in get_contenttypes_and_models content_types = { File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 280, in __iter__ self._fetch_all() File "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/app/.heroku/python/lib/python3.10/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 "/app/.heroku/python/lib/python3.10/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 79, in _execute with self.db.wrap_database_errors: File "/app/.heroku/python/lib/python3.10/site-packages/django/db/utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "/app/.heroku/python/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: relation "django_content_type" does not exist LINE 1: ..."."app_label", "django_content_type"."model" FROM "django_co...
环境与配置信息
- 本地原使用
db.sqlite3数据库 settings.py核心配置:
INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_elasticsearch_dsl', 'psycopg2', 'malbucket' ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgres', } } DATABASES["default"] = dj_database_url.config(default=urllib.parse.quote(os.environ.get("DATABASE_URL", "").encode("utf-8")))
当前数据库状态
执行manage.py dbshell后显示的表列表:
List of relations Schema | Name | Type | Owner --------+-------------------+-------+---------------- public | django_migrations | table | <name> public | django_session | table | <name>
迁移标记状态
执行heroku run python manage.py showmigrations结果:
admin [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial
解决方案
1. 重置数据库迁移记录
进入Heroku PostgreSQL数据库shell:
heroku pg:psql
删除迁移记录表中的所有记录:
DELETE FROM django_migrations;
退出数据库shell:
\q
2. 修正数据库引擎配置
修改settings.py中的数据库引擎,将postgres改为postgresql(Django官方标准写法):
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', } }
修改后重新部署代码到Heroku:
git add settings.py git commit -m "fix database engine typo" git push heroku main
3. 按依赖顺序重新执行迁移
先迁移contenttypes(它是auth、admin等应用的核心依赖):
heroku run python manage.py migrate contenttypes
接着依次迁移其他核心应用:
heroku run python manage.py migrate auth heroku run python manage.py migrate admin heroku run python manage.py migrate sessions
最后迁移自定义应用和第三方应用:
heroku run python manage.py migrate malbucket
4. 修复迁移标记(若仍有不一致)
如果showmigrations显示迁移已标记为应用,但实际表不存在,执行以下命令:
heroku run python manage.py migrate --fake-initial
5. 验证修复结果
执行命令检查django_content_type表是否存在:
heroku run python manage.py inspectdb | grep django_content_type
或进入数据库shell查看全量表列表:
heroku pg:psql \dt
内容的提问来源于stack exchange,提问作者Finch
相关产品推荐
相关产品推荐

