Django에 PostgreSQL 연동하기
(windows 환경에서 설치)
장고에서 postgresql을 연동시키기 위해서는 가장먼저 postgreSQL을 설치한다
공식사이트 👉 https://www.postgresql.org/
- Download 클릭 후 설치한다
- pwd를 입력한다 (나중에 써야하기 때문에 기억해야 한다)
- 주로 5432의 포트번호를 사용하니 포트를 5432로 설정한다
- stack bulider 설치여부는 체크를 해제한다
설치가 끝나면 설치된 경로(C:\ProgramData\Microsoft\Windows\Start Menu\Programs\PostgreSQL 14)에 pgAdmin4
와
SQL Shell
로 데이터베이스를 create할 수 있다
shell로 db를 생성해보면,
- shell로 접속한다
pwd를 제외하고 enter를 친다(default값으로 설정)
erver [localhost]:
Database [postgres]:
Port [5432]:
Username [postgres]:
postgres 사용자의 암호: 암호입력
psql (14.1)
- db를 생성한다
\l로 생성한 db를 확인한다
postgres=# CREATE DATABASE database_name;
postgres=# \l
- user와 pwd를 지정하고 권한을 부여한다
postgres= CREATE USER user_id WITH PASSWORD "password";
postgres= ALTER ROLE user_id SET client_encoding TO 'utf8';
postgres= ALTER ROLE user_id SET default_transaction_isolation TO 'read committed';
postgres= ALTER ROLE user_id SET timezone TO 'UTC';
# 권한주기
postgres= GRANT ALL PRIVILEGES ON DATABASE database_name TO user_id;
postgres= alter user scott with superuser;
postgres= alter user scott with createdb;
postgres= alter user scott with createrole;
postgres= alter user scott with replication;
postgres= alter user scott with bypassrls;
# 부여된 권한 확인
postgres= \du
이후 장고에 DB에 생성한 database를 연동시킨다
이때 연동시키기 위해서는 psycopg2 패키지를 설치해야 한다. 이때 pip install psycopg2
는 windows에서는 error가 발생한다
이를 해결하기 위해서는 sudo apt-get install libpq-dev python-dev
를 먼저 설치한 후 설치하면 된다
DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "partner",
"USER": "admin",
"PASSWORD": env("PASSWORD"),
"HOST": "localhost",
"PORT": "5432"
}
}
이후에도 계속 django.db.utils.OperationalError
에러가 발생했다. 근데 이문제는 NAME과 USER를 env로 값을 받아오지 않고 값을 그대로 써주면
해결되었다. 왜 그런지는 아직 잘모르겠다 😂
reference
https://doorbw.tistory.com/179?category=711158
https://doorbw.tistory.com/183
postgre GUI로 설정 -https://initstory.tistory.com/19
https://seulcode.tistory.com/111
http://web.archive.org/web/20140615091953/http://goshawknest.wordpress.com/2011/02/16/how-to-install-psycopg2-under-virtualenv/