1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

仮想環境でDjangoとPostgreSQLを5分で接続する方法

Posted at

前提

  • Windows 10を使用
  • 仮想環境上でpipコマンドが使用できる(pip --versionで確認)
  • django-admin startprojectコマンドを実行済み

下準備

仮想環境でPostgreSQLをダウンロード

pip install psycopg2

ダウンロードできているか確認

pip freeze

仮想環境にダウンロードしたパッケージが表示される

postgreSQLの設定

PostgreSQLに接続

psql -U postgres

データベース作成&ユーザーへの権限付与

CREATE DATABASE [database名];
CREATE USER [ユーザー名] WITH PASSWORD 'password';
GRANT ALL PRIVILEGES ON DATABASE [db名] TO [ユーザー名];

データベースを抜ける

\q または exit

Django側の設定

変更するのはsettings.pyだけ

settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'django_proj_db', # 作成したデータベース名
        'USER': 'admin', # 作成したユーザー名
        'PASSWORD': '1234', # パスワード
        'HOST': 'localhost', # localhostがデフォルト
        'PORT': '5432' # 基本設定で5432
    }
}

postgressにログイン

python manage.py dbshell # settings.pyに登録したデータベースに接続できる

接続情報確認

django_blog_db=> \conninfo
出力⇒データベース"django_blog_db" にユーザ "admin" として、ホスト "localhost" 上のポート "5432" を介して接続しています。

PostgreSQL コマンドシート

下記の記事が参考になります。
https://qiita.com/Shitimi_613/items/bcd6a7f4134e6a8f0621

参考

今回は下記の記事を基に自分なりに作りました。
https://hodalog.com/initial-setting-to-use-postgresql-in-django/

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?