Djangoアプリケーション開発(2) DjangoインストールからDB設定、runserverまで
前のエントリで立ち上げたPython仮想環境にDjangoをインストールしてからrunserverするまで。
d5ono.hatenablog.com
ヴァージョン情報:
Python 3.5.2
Django 1.11.2
PostgreSQL 9.5
目次
1. Djangoインストール
Python仮想環境に入る。
(venv) ubuntu@ubuntu-xenial:/vagrant$ pip3 install django
2. プロジェクト立ち上げ
(venv) ubuntu@ubuntu-xenial:/vagrant$ django-admin startproject projrct_name
3. システムへのアクセスを許可するホストを設定
project_name/project_name/settings.py を編集
ALLOWED_HOSTS = ['*']
4. DB設定・マイグレーション
python仮想環境に入り、PostgreSQLのドライバをインストールする。
(venv) ubuntu@ubuntu-xenial:/vagrant$ pip3 install psycopg2
つぎに、postgresユーザのUNIXパスワードを設定する。
PostgreSQLをインストールした時点でPostgreSQL管理用のUNIXユーザpostgres
が作成されるが、パスワードが未設定のためUNIXログインができない。
いったんpython仮想環境を出る。
ubuntu@ubuntu-xenial:/$ sudo passwd postgres
Enter new UNIX password: postgresの新しいUNIXパスワード
Retype new UNIX password: postgresの新しいUNIXパスワード
passwd: password updated successfully
作成。ログインしてみる。
ubuntu@ubuntu-xenial:/$ su postgres
Password: postgresのUNIXパスワード
postgres@ubuntu-xenial:/$
次に、PostgreSQLにログインするためのpostgresのパスワードを設定する。
こちらを参考にさせて頂いた。
qiita.com
ubuntu@ubuntu-xenial:~$ sudo su postgres -c "psql --username=postgres"
psql (9.5.8)
Type "help" for help.
postgres=# ALTER USER postgres with encrypted password 'postgresのDBパスワード';
Peer認証を外す。
ubuntu@ubuntu-xenial:~$ sudo vi /etc/postgresql/9.5/main/pg_hba.conf
以下に編集。
local all dbuser peer
local all all peer
↓
local all dbuser md5
local all all md5
postgresql 再起動。
ubuntu@ubuntu-xenial:~$ sudo /etc/init.d/postgresql restart
これで、PostgreSQLにpostgresユーザでログインできるようになる。
ubuntu@ubuntu-xenial:~$ psql -U postgres
Password for user postgres: postgresのDBパスワード'
psql (9.5.8)
Type "help" for help.
postgres=#
これから作るDjangoシステムのデータベースユーザ作成。
ubuntu@ubuntu-xenial:~$ su - postgres
Password: <= UNIXのpostgresユーザパスワード
postgres@ubuntu-xenial:~$ createuser -P dbuser
Enter password for new role: dbpassword
Enter it again: dbpassword
Password: <= postgresのDBパスワード'
DB作成。
postgres@ubuntu-xenial:~$ createdb dbname -O dbuser
Password: <= postgresのDBパスワード'
DBログインする時。
postgres@ubuntu-xenial:~$ psql -U dbuser -W -d dbname
Password for user dbuser: dbpassword
psql (9.5.7)
Type "help" for help.
dbname=>
DB接続設定。
project_name/project_name/settings.py を編集
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'dbname',
'USER': 'dbuser',
'PASSWORD': 'dbpassword',
'HOST': 'localhost',
'PORT': '5432',
}
}
DBマイグレーション。
実行パスを通した後で以下を実行。
(venv) ubuntu@ubuntu-xenial:/vagrant/project_name$ ./manage.py makemigrations
(venv) ubuntu@ubuntu-xenial:/vagrant/project_name$ ./manage.py migrate
https://docs.djangoproject.com/ja/1.11/topics/migrations
5. Django管理ユーザ作成
(venv) ubuntu@ubuntu-xenial:/vagrant/project_name$ ./manage.py createsuperuser
6. django開発サーバ起動
(venv) ubuntu@ubuntu-xenial:/vagrant/project_name$ ./manage.py runserver 0.0.0.0:8000
7. ブラウザアクセス
http://192.168.33.10:8000/
Django管理側サイト:http://192.168.33.10:8000/admin/login/