简体   繁体   English

如何在 Django 中设置 PostgreSQL 数据库

[英]How to set up a PostgreSQL database in Django

I'm new to Python and Django.我是 Python 和 Django 的新手。

I'm configuring a Django project using a PostgreSQL database engine backend, But I'm getting errors on each database operation.我正在使用 PostgreSQL 数据库引擎后端配置 Django 项目,但每次数据库操作都会出错。 For example when I run manage.py syncdb , I'm getting:例如,当我运行manage.py syncdb时,我得到:

C:\xampp\htdocs\djangodir>python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 11, in <module>
    execute_manager(settings)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
438, in execute_manager
    utility.execute()
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
261, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "C:\Python27\lib\site-packages\django\core\management\__init__.py", line
67, in load_command_class
    module = import_module('%s.management.commands.%s' % (app_name, name))
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
    __import__(name)
  File "C:\Python27\lib\site-packages\django\core\management\commands\syncdb.py"
, line 7, in <module>
    from django.core.management.sql import custom_sql_for_model, emit_post_sync_
signal
  File "C:\Python27\lib\site-packages\django\core\management\sql.py", line 6, in
 <module>
    from django.db import models
  File "C:\Python27\lib\site-packages\django\db\__init__.py", line 77, in <modul
e>
    connection = connections[DEFAULT_DB_ALIAS]
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 92, in __getitem
__
    backend = load_backend(db['ENGINE'])
  File "C:\Python27\lib\site-packages\django\db\utils.py", line 33, in load_back
end
    return import_module('.base', backend_name)
  File "C:\Python27\lib\site-packages\django\utils\importlib.py", line 35, in im
port_module
    __import__(name)
  File "C:\Python27\lib\site-packages\django\db\backends\postgresql\base.py", li
ne 23, in <module>
    raise ImproperlyConfigured("Error loading psycopg module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading psycopg module: No mo
dule named psycopg

Can someone give me a clue on what is going on?有人可以告诉我发生了什么吗?

You need to install psycopg2 Python library.您需要安装psycopg2 Python 库。

Installation安装


Download http://initd.org/psycopg/ , then install it under Python PATH下载http://initd.org/psycopg/ ,然后在 Python PATH 下安装

After downloading, easily extract the tarball and:下载后,轻松解压 tarball 并:

$ python setup.py install

Or if you wish, install it by either easy_install or pip .或者,如果您愿意,可以通过easy_installpip安装它。

( I prefer to use pip over easy_install for no reason. ) 我更喜欢使用 pip 而不是 easy_install。

  • $ easy_install psycopg2
  • $ pip install psycopg2

Configuration配置


in settings .py设置.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'db_name',                      
        'USER': 'db_user',
        'PASSWORD': 'db_user_password',
        'HOST': '',
        'PORT': 'db_port_number',
    }
}

- Other installation instructions can be found at download page and install page . - 其他安装说明可在下载页面安装页面找到

Also make sure you have the PostgreSQL development package installed.还要确保您已安装 PostgreSQL 开发包。 On Ubuntu you need to do something like this:在 Ubuntu 上,您需要执行以下操作:

$ sudo apt-get install libpq-dev

Step by step that I use:我使用的一步一步:

 - sudo apt-get install python-dev
 - sudo apt-get install postgresql-server-dev-9.1
 - sudo apt-get install python-psycopg2 - Or sudo pip install psycopg2

You may want to install a graphic tool to manage your databases, for that you can do:您可能需要安装一个图形工具来管理您的数据库,您可以这样做:

sudo apt-get install postgresql pgadmin4 

After, you must change Postgre user password, then do:之后,您必须更改 Postgre 用户密码,然后执行:

 - sudo su
 - su postgres -c psql postgres
 - ALTER USER postgres WITH PASSWORD 'YourPassWordHere';
 - \q

On your settings.py file you do:在您的 settings.py 文件中,您可以:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': '',
        'PORT': '',
    }
}

Extra:额外的:

If you want to create the db using the command line you can just do:如果你想使用命令行创建数据库,你可以这样做:

- sudo su
- su postgres -c psql postgres
- CREATE DATABASE dbname;
- CREATE USER djangouser WITH ENCRYPTED PASSWORD 'myPasswordHere';
- GRANT ALL PRIVILEGES ON DATABASE dbname TO djangouser;

On your settings.py file you do:在您的 settings.py 文件中,您可以:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'djangouser',
        'PASSWORD': 'myPasswordHere',
        'HOST': '',
        'PORT': '',
    }
}

You can install "psycopg" with the following command:您可以使用以下命令安装“psycopg”:

# sudo easy_install psycopg2

Alternatively, you can use pip :或者,您可以使用 pip :

# pip install psycopg2

easy_install and pip are included with ActivePython , or manually installed from the respective project sites. easy_install 和 pip 包含在ActivePython中,或者从各自项目站点手动安装。

Or, simply get the pre-built Windows installer .或者,只需获取预构建的 Windows 安装程序

This may seem a bit lengthy, but it worked for me without any error.这可能看起来有点冗长,但它对我有用,没有任何错误。

At first, Install phppgadmin from Ubuntu Software Center.首先,从 Ubuntu 软件中心安装 phppgadmin。

Then run these steps in terminal.然后在终端中运行这些步骤。

sudo apt-get install libpq-dev python-dev
pip install psycopg2
sudo apt-get install postgresql postgresql-contrib phppgadmin

Start the apache server启动apache服务器

sudo service apache2 start

Now run this too in terminal, to edit the apache file.现在在终端中也运行它,以编辑 apache 文件。

sudo gedit /etc/apache2/apache2.conf

Add the following line to the opened file:将以下行添加到打开的文件中:

Include /etc/apache2/conf.d/phppgadmin

Now reload apache.现在重新加载apache。 Use terminal.使用终端。

sudo /etc/init.d/apache2 reload

Now you will have to create a new database.现在您必须创建一个新数据库。 Login as 'postgres' user.以“postgres”用户身份登录。 Continue in terminal.继续在终端。

sudo su - postgres

In case you have trouble with the password of 'postgres', you can change it using the answer here https://stackoverflow.com/a/12721020/1990793 and continue with the steps.如果您对“postgres”的密码有疑问,您可以使用此处的答案https://stackoverflow.com/a/12721020/1990793进行更改,然后继续执行这些步骤。

Now create a database现在创建一个数据库

createdb <db_name>

Now create a new user to login to phppgadmin later, providing a new password.现在创建一个新用户稍后登录 phppgadmin,提供一个新密码。

createuser -P <new_user>

Now your postgressql has been setup, and you can go to:现在你的 postgressql 已经设置好了,你可以去:

http://localhost/phppgadmin/

and login using the new user you've created, in order to view the database.并使用您创建的新用户登录,以查看数据库。

直接的问题似乎是您缺少psycopg2模块。

If you are using Fedora 20, Django 1.6.5, postgresql 9.3.* and you need the psycopg2 module, do this:如果您使用 Fedora 20、Django 1.6.5、postgresql 9.3.* 并且需要 psycopg2 模块,请执行以下操作:

yum install postgresql-devel
easy_install psycopg2

If you are like me, you may have trouble finding the well documented libpq-dev rpm... The above worked for me just now.如果你像我一样,你可能很难找到有据可查的 libpq-dev rpm... 以上刚刚对我有用。

I was having the same Issue on Mac .我在Mac上遇到了同样的问题。

The solution was to use only PIP to install everything, and touch some things.解决方案是只使用PIP来安装所有东西,并触摸一些东西。

First install PIP from: https://pip.pypa.io/en/latest/首先从以下位置安装 PIP: https ://pip.pypa.io/en/latest/

Then you want to make sure if path to pg_config is in your PATH (echo $PATH), if not you can edit your bash_profile:然后你要确定pg_config的路径是否在你的PATH (echo $PATH) 中,如果没有,你可以编辑你的 bash_profile:

vi /Users/<user>/.bash_profile

and add this line:并添加这一行:

export PATH=$PATH:/path/to/pg_config/bin

If you don't know where pg_config is you can use the "locate" tool, but be sure your locate.db is up to date (i was using an old locate.db and using paths that does not exists).如果您不知道 pg_config 在哪里,您可以使用“定位”工具,但请确保您的 locate.db 是最新的(我使用的是旧的 locate.db 并使用不存在的路径)。

sudo /usr/libexec/locate.updatedb
locate pg_config

Then install Django (if needed) and psycopg2.然后安装 Django(如果需要)和 psycopg2。

sudo pip install Django
sudo pip install psycopg2

And then in settings.py (localhost:defaultport)然后在 settings.py (localhost:defaultport)

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': '',
        'PORT': '',
    }
}

Greets!问候!

$ sudo apt-get install libpq-dev

Year, this solve my problem.年,这解决了我的问题。 After execute this, do: pip install psycopg2执行此操作后,执行: pip install psycopg2

Steps to create a Django app with PostgreSQL database from scratch.从头开始使用 PostgreSQL 数据库创建 Django 应用程序的步骤。

  1. Check if PostgreSQL is installed in your system.检查您的系统中是否安装了 PostgreSQL。 In your bash shell enter在你的 bash shell 中输入

    psql --version
  2. If PostgreSQL is installed jump to step 6.如果安装了 PostgreSQL,请跳转到第 6 步。

  3. To install PostgreSQL -安装 PostgreSQL -

     sudo apt-get install python3-dev libpq-dev sudo apt-get install postgresql postgresql-contrib
  4. By default PostgreSQL installation creates a special user named "postgres" that has all rights.默认情况下,PostgreSQL 安装会创建一个名为“postgres”的特殊用户,该用户拥有所有权限。 To login to PostgreSQL登录 PostgreSQL

     sudo -u postgres psql

    To exit PostgreSQL session退出 PostgreSQL 会话

    \q
  5. Now set password for "postgres" user.现在为“postgres”用户设置密码。

    Login to PostgreSQL -登录到 PostgreSQL -

     sudo -u postgres psql

    In PostgreSQL interactive session enter -在 PostgreSQL 交互式会话中输入 -

     \password postgres
  6. Create PostgreSQL database.创建 PostgreSQL 数据库。

    To create directly from bash shell -直接从 bash shell 创建 -

     sudo -u postgres createdb your_db_name

    To create from PostgreSQL interactive session -从 PostgreSQL 交互式会话创建 -

     createdb your_db_name

    To check if the database is created, list all databases using PostgreSQL command要检查数据库是否已创建,请使用 PostgreSQL 命令列出所有数据库

    \l
  7. If you already have an existing Django project then jump to step 11. Otherwise create a virtual environment.如果您已经有一个现有的 Django 项目,则跳转到第 11 步。否则创建一个虚拟环境。 I use virtualenv wrapper.我使用 virtualenv 包装器。

     mkvirtualenv your_project_name
  8. Create Django project.创建 Django 项目。

     django-admin startproject your_project_name
  9. Cd to the project directory and create your app. cd 到项目目录并创建您的应用程序。

     python manage.py startapp your_app_name
  10. Install Django.安装 Django。

     pip install django
  11. Install Psycopg2.安装 Psycopg2。 Psycopg2 is a PostgreSQL database adapter for Python. Psycopg2 是 Python 的 PostgreSQL 数据库适配器。 This is required for Django to connect with PostgreSQL.这是 Django 连接 PostgreSQL 所必需的。

     pip install psycopg2
  12. Update settings.py as follows更新 settings.py 如下

    DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'your_db_name', 'USER': 'postgres', 'PASSWORD': 'xxxxx', 'HOST': 'localhost', 'PORT': '', } }
  13. Run migration.运行迁移。

     python3 manage.py migrate
  14. Run Django server and visit localhost:8000运行 Django 服务器并访问 localhost:8000

     python3 manage.py runserver 0.0.0.0:8000
  15. If required you can install pgadmin - a graphical client to view and manipulate PostgreSQL database schema and data.如果需要,您可以安装 pgadmin - 一个图形客户端来查看和操作 PostgreSQL 数据库模式和数据。

Please note that installation of psycopg2 via pip or setup.py requires to have Visual Studio 2008 (more precisely executable file vcvarsall.bat ).请注意,通过 pip 或 setup.py 安装psycopg2需要具有 Visual Studio 2008(更准确地说是可执行文件vcvarsall.bat )。 If you don't have admin rights to install it or set the appropriate PATH variable on Windows, you can download already compiled library from here .如果您没有管理员权限来安装它或在 Windows 上设置适当的 PATH 变量,您可以从此处下载已编译的库。

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server.这是在 ubuntu 服务器中设置PostgreSQL的非常好的一步一步的过程之一。 I have tried it with Ubuntu 16.04 and its working.我已经用Ubuntu 16.04和它的工作进行了尝试。

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04 https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

integrating postgresql in django在 django 中集成 postgresql

Arch: Ubuntu and Nginx Arch:Ubuntu 和 Nginx

sudo apt install libpq-dev postgresql postgresql-contrib

systemctl status postgresql.service is usually active by now if not check back installation如果不检查安装, systemctl status postgresql.service现在通常处于活动状态

By default, Postgres uses an authentication scheme called “ peer authentication ” for local connections.默认情况下,Postgres 使用称为“对等身份验证”的身份验证方案进行本地连接。 Basically, this means that if the user's operating system username john@example matches a valid Postgres username john , that user can login with no further authentication.基本上,这意味着如果用户的操作系统用户名john@example与有效的 Postgres 用户名john匹配,则该用户无需进一步身份验证即可登录。 During the Postgres installation, an operating system user named postgres was created to correspond to the postgres administrative user.在 Postgres 安装期间,创建了一个名为postgres的操作系统用户以对应于postgres管理用户。 We use this user to perform administrative tasks.我们使用此用户来执行管理任务。

sudo -u postgres psql

postgres=# create database example;
CREATE DATABASE
postgres=# create user john with password 'abcxyz';
CREATE ROLE
postgres=# ALTER ROLE john SET client_encoding TO 'utf8';
postgres=# ALTER ROLE john SET default_transaction_isolation TO 'read committed';
postgres=# ALTER ROLE john SET timezone TO 'UTC';
postgres=# GRANT ALL PRIVILEGES ON DATABASE example TO john;

Postgres is now set up so that Django can connect to and manage its database information. Postgres 现在已设置好,以便 Django 可以连接并管理其数据库信息。

pip install psycopg2-binary is not recommended for production as psycopg2 has unfixed issues.不建议将pip install psycopg2-binary用于生产,因为psycopg2存在未修复的问题。

settings.py设置.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'example',
        'USER': 'john',
        'PASSWORD': 'abcxyz',
        'HOST': 'localhost',
        'PORT': '5432',  can be left empty
    }
}

At the end, use these basic django migration commands to complete the integration.最后,使用这些基本的 django 迁移命令来完成集成。

python manage.py makemigrations

python manage.py migrate

Extra TODO Tips额外的 TODO 提示

It is highly recommended to use better methods to set critical values like NAME, USER and PASSWORD rather than using plain text like shown above in database code snippet.强烈建议使用更好的方法来设置关键值,例如 NAME、USER 和 PASSWORD,而不是使用上面数据库代码片段中显示的纯文本。

One method could be using a json file to replace those contents from outside the scope of project root directories.一种方法是使用 json 文件从项目根目录范围之外替换这些内容。 So even in unforeseeable cases of attempted source code hijacking your critical auth details could be out of reach.因此,即使在无法预见的尝试源代码劫持您的关键身份验证详细信息的情况下,也可能遥不可及。

A new config.json file with corresponding key-value pairs is assumed to be created.假定创建了一个具有相应键值对的新config.json文件。

{
  "POSTGRES_DB": "example",
  "POSTGRES_USER": "john",
  "POSTGRES_PASSWORD": "abcxyz",
  "POSTGRES_HOST": "localhost",
  "POSTGRES_PORT": ""
}

Placing this code in settings.py to load and use config.json .将此代码放在settings.py中以加载和使用config.json

import os
import json

with open('/path to your config.json file/') as config_file:
    config = json.load(config_file)

Update database config to load the params from config.json file:更新数据库配置以从config.json文件加载参数:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': config['POSTGRES_DB'],
        'USER': config['POSTGRES_USER'],
        'PASSWORD': config['POSTGRES_PASSWORD'],
        'HOST': config['POSTGRES_HOST'],
        'PORT': config['POSTGRES_PORT'],
    }
}

postgres 14 在端口 5433 上运行在 settings.py 中指定

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM