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

如何在PythonAnywhere上配置Django连接PostgreSQL数据库?

Django站点部署到PythonAnywhere时PostgreSQL认证失败问题

我上传了一个经少量修改的基础Django「Hello World」站点,数据库配置为PostgreSQL,本地运行正常,但在PythonAnywhere(以下简称PA)完成配置时遇到问题。

在PA上创建PostgreSQL数据库的步骤

我基于PostgreSQL 15版本的权限变更建议(本地使用v15)执行了以下创建步骤,假设适用于PA的v12版本,可能存在错误:

CREATE DATABASE domain_db;

CREATE USER domain_admin WITH PASSWORD '123456789';

\connect domain_db;

CREATE SCHEMA domain_schema AUTHORIZATION domain_admin;

-- Django文档推荐的设置
ALTER ROLE domain_admin SET client_encoding TO 'utf8';
ALTER ROLE domain_admin SET default_transaction_isolation TO 'read committed';
ALTER ROLE domain_admin SET timezone TO 'UTC';

项目目录结构

domain/
    site/
        _config/
            settings/
                base.py           本地和生产环境通用配置
                local.py          本地开发配置
                production.py     生产服务器配置
            asgi.py
            urls.py
            wsgi.py
        staticfiles/
        manage.py
    venv
    .env

Django数据库配置(base.py)

我在base.py中通过加载.env文件的环境变量配置数据库,已确认.env文件加载正常:

BASE_DIR = Path(__file__).resolve().parent.parent.parent
...
env = environ.Env()
env_file_path = BASE_DIR.parent / ".env"
env.read_env(env_file_path)
...
DATABASES = {
    'default': {
        "ENGINE": env("ENGINE"),
        "OPTIONS": env.json("OPTIONS", default={}),
        "NAME": env("NAME"),
        "USER": env("USER"),
        "PASSWORD": env("PASSWORD"),
        "HOST": env("HOST"),
        "PORT": env("PORT"),
    }
}

.env文件相关配置(已修改敏感数据)

ALLOWED_HOSTS=www.<domain>.com,<domain>.com

# Database
ENGINE=django.db.backends.postgresql
OPTIONS={"options": "-c search_path=domain_schema"}
NAME=domain_db
USER=domain_admin
PASSWORD=123456789
HOST=<prefix>.postgres.pythonanywhere-services.com
PORT=<port provided by PA>

执行makemigrations时的错误信息(已编辑)

/django/core/management/commands/makemigrations.py:160: 

RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default':

connection failed: connection to server at "xx.xx.xx.xx", port <xxxxx> failed:

FATAL:  password authentication failed for user <user> connection to server at "xx.xx.xx.xx.", port <xxxxx> failed:

FATAL:  password authentication failed for user <user>

已完成的验证操作

我通过以下psql命令验证了数据库连接正常:

psql -h <prefix>.postgres.pythonanywhere-services.com -U domain_admin -d domain_db -p <port>

疑问

我认为.env设置正确,但不确定下一步操作:

  • 是否还有其他需要配置的项?
  • PostgreSQL v12与v15的配置差异是否过大导致问题?
  • 能否将PA上的PostgreSQL升级到v15以匹配本地环境?

内容的提问来源于stack exchange,提问作者martin's

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 06:44:51