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

Django连接PostgreSQL时出现密码认证失败问题求助

Django切换PostgreSQL时密码认证失败的解决办法

问题概述

在virtualenv环境中开发Django项目,已安装psycopg2-binary,将数据库从SQLite3切换为PostgreSQL后,修改了settings.py的数据库配置:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'database',
        'USER': 'user',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

执行python manage.py runserver时出现以下错误:

psycopg2.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL:  password authentication failed for user "user"
django.db.utils.OperationalError: connection to server at "localhost" (127.0.0.1), port 5432 failed: FATAL:  password authentication failed for user "user"

解决步骤

1. 手动验证PostgreSQL连接合法性

通过psql命令直接测试连接,确认用户名、密码、数据库名是否正确:

psql -U user -d database -h localhost -p 5432

执行后输入配置中的mypassword,若无法连接:

  • 若提示用户不存在,先创建用户并赋予数据库权限:
    # 以postgres用户身份进入PostgreSQL命令行
    sudo -u postgres psql
    # 创建指定用户
    CREATE USER user WITH PASSWORD 'mypassword';
    # 赋予目标数据库全部操作权限
    GRANT ALL PRIVILEGES ON DATABASE database TO user;
    # 退出命令行
    \q
    
  • 若提示数据库不存在,创建目标数据库:
    createdb -U user database
    

2. 调整PostgreSQL的认证策略

PostgreSQL的pg_hba.conf文件控制连接认证规则,常见问题是本地连接未启用密码认证:

  1. 定位配置文件路径:
    • Ubuntu/Debian:/etc/postgresql/<你的PostgreSQL版本>/main/pg_hba.conf
    • CentOS/RHEL:/var/lib/pgsql/<你的PostgreSQL版本>/data/pg_hba.conf
  2. 修改本地连接的认证方式为md5:
    # Unix域套接字连接
    local   all             all                                     md5
    # IPv4本地连接
    host    all             all             127.0.0.1/32            md5
    # IPv6本地连接
    host    all             all             ::1/128                 md5
    
  3. 重启PostgreSQL服务使配置生效:
    # Ubuntu/Debian
    sudo systemctl restart postgresql
    # CentOS/RHEL(替换为你的PostgreSQL版本号)
    sudo systemctl restart postgresql-15
    

3. 确认Django配置的准确性

  • 检查settings.py中NAME是否为PostgreSQL中已存在的数据库名称,USER和PASSWORD与PostgreSQL中的配置完全匹配(PostgreSQL默认对标识符不区分大小写,除非创建时用双引号强制区分)
  • 排查配置中是否存在多余空格或拼写错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:38