从 SQLite 切换到 postgres,postgres 要求输入密码

Switch from SQLite to postgres, postgres asking for a password

有两点需要注意:第一,我在我的虚拟环境 运行ning 中执行这些命令。所以终端显示为 (env):。第二,每次我尝试输入 su postgres 时,它都会要求我输入密码。

我正在读一本关于 Django 的书(使用 mac),书上说: "If you are using macOS, download PostgreSQL from https://www.postgresql.org/download/ and install it. You also need to install the Psycopg2 PostgreSQL adapter for Python. Run the following command to install it: pip install psycopg2==2.7.4."

我已经在我的 machine 上安装了 postgres,因为我之前在尝试部署网站时摸索着,然后才回到我构建的这个示例项目。所以我没有去网站安装它。我按照说明安装了 psycopg2 ((env): pip install psycopg2==2.7.4.)

"Let's create a user for our PostgreSQL database. Open the shell and run the following commands: su postgres then createuser -dP blog"

我在想"open the shell"是进入python虚拟shell?所以:

python manage.py shell

然后

su postgres

这没有用,它要求我输入密码。退出了shell,运行同样的命令(env): su postgres,同样的结果。

从那里我想也许因为我在虚拟环境中,所以我必须重新下载 postgres。我 运行 pip install postgres (不知道这是否会下载一些东西,但它确实下载了,所以我没有费心去 website/also 不知道如何将它安装到这个环境网站)。请注意,这安装了 postgres 以及 psycopg-someversion-binary。所以现在我安装了 psycopg2==2.7.4psycopg2-binary 的某个版本。从那里我 运行 (env): su postgres (来自我的环境的注释)。同样的结果,它要求输入密码。

然后我重新进入 python 交互式 shell 与 python manage.py shell 并再次 运行 su postgres。同样的结果。

至此,我试着自己研究一下。我读到的内容是我需要通过在终端输入 sudo -i 从 root(?) 运行 su - postgres。我这样做了,现在我在 Justins-MBP:~ root#(这似乎与我尝试使用 postgres 数据库的 django 项目完全无关)。无论如何,从这里 su - postgres 开始,您可能已经猜到了,它要求我输入密码。

非常感谢任何关于如何正确切换数据库的帮助。

此外,在输入所有这些内容并思考我所做的事情后,我意识到我还没有更改 python 项目的数据库设置。但是这本书也没有,所以不太确定这个项目怎么会知道这个数据库?

您可能还没有在 MacOS 上设置 root 用户,请参阅 this SO answer. However, for more information about the use of su, see this answer with a link to Apple's tech notes on how to create one

你应该在你的 macOS 终端上这样做的原因是你在 PostrgreSQL 数据库上设置、配置和执行数据库操作,而这本身,按照你的书描述的方式,与 Django 无关(或 Python 就此而言)。

因此,您必须确保 1) PostgreSQL 安装在您的设备上,并且 2) 您拥有 PostgreSQL 运行ning(因为您将创建用户,这实际上意味着将数据插入您的 PostgreSQL数据库)。我过去使用 this blogpost(非附属)在 MacOS 上设置(安装、运行 和配置)PostgreSQL。

关于 Django,您需要在 settings.py 中更改 DATABASES(另请参阅 Django 教程中的 this 部分)

DATABASES = {
    # default namespace
    'default': { 
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'dbname' #name of the database,
        'USER': 'username' #name of the created user,
        'PASSWORD': 'password',
        'HOST': '127.0.0.1' #when local,
        'PORT': '5432' #default psql port,
    }
}