You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

部署Django+SQLite3至Heroku时创建超级用户遇数据库错误求助

解决方案

1. 修复数据库配置(解决DATABASE_URL警告)

Heroku不支持SQLite3(文件型数据库,Heroku文件系统为临时存储),必须改用PostgreSQL。请确保settings.py中的数据库配置正确读取Heroku的DATABASE_URL环境变量:

import os
import dj_database_url
from pathlib import Path

# 本地开发默认SQLite配置
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# 生产环境(Heroku)覆盖为PostgreSQL配置
if 'DATABASE_URL' in os.environ:
    DATABASES['default'] = dj_database_url.config(conn_max_age=600, ssl_require=True)

需先在requirements.txt中添加依赖包dj-database-url>=2.0.0,再重新推送代码至Heroku。

2. 强制Heroku执行完整迁移

你遇到的迁移异常,大概率是之前的migrate命令实际指向了临时SQLite库而非PostgreSQL。按以下步骤操作:

  • 重置Heroku数据库:
    heroku pg:reset DATABASE --confirm 你的应用名称
    
  • 推送修正后的代码:
    git add .
    git commit -m "Fix Heroku database config"
    git push heroku main
    
  • 无交互执行迁移:
    heroku run python manage.py migrate --noinput
    
  • 再次创建超级用户:
    heroku run python manage.py createsuperuser
    

3. 同步本地与Heroku的迁移文件

本地无待执行迁移但Heroku提示未应用,可能是本地迁移文件未提交至Git:

  • 检查未提交的迁移文件:
    git status
    
  • 提交所有迁移文件:
    git add */migrations/*.py
    git commit -m "Push all migration files"
    git push heroku main
    

额外检查项

  • 用heroku config命令确认DATABASE_URL环境变量存在,Heroku绑定PostgreSQL实例后会自动生成该变量。
  • 禁止在Heroku生产环境使用SQLite3,所有数据库操作必须基于PostgreSQL。

内容的提问来源于stack exchange,提问作者jowww

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 23:40:05