Heroku x Django x Cloud9


cloud9でDjangoのWebアプリを作って、それをHerokuにデプロイするためのメモ

CLOUD9

create a new project

confilm your workspace name
choose a template -> djnago

create workspace

remove all (include .gitignore .env etc...)

CHANGE PYTHON VERSION

  $ sudo unlink /usr/bin/python
  $ sudo ln -s /usr/bin/python3 /usr/bin/python

Install djnago for python3

 $ sudo pip install django-toolbelt

Create your django project

  $ django-admin startproject <project_name>

Edit //settings.py

  ALLOWED_HOSTS = ["*"]
  <japanese>

Make new project

   $ cd <project_name>
   $ python manage.py startapp <app-name>

RUN YOUR SERVICE

  $ python manage.py migrate
  $ python manage.py runserver $IP:$PORT

remoteserver
  $ python manage.py runserver 0.0.0.0:8000

WARNING DIRECTORY!!

MAKE FILE /.gitignore

  *.pyc
  staticfiles
  db.sqlite3

git 初期化

  $ git init
  $ git add .
  $ git commit -m "Djangoアプリを作成した"

heroku用設定

  $ echo "web: gunicorn <project_name>.wsgi --log-file -" > Procfile

  $ echo "python-3.6.4" > runtime.txt

  $ pip freeze > requirements.txt
MINIMUM
  dj-database-url==0.5.0
  Django==2.0.3
  gunicorn==19.7.1
  psycopg2==2.7.1
  pytz==2017.2

Add //settings.py

  # Parse database configuration from $DATABASE_URL
  import dj_database_url
  db_from_env = dj_database_url.config()
  DATABASES['default'].update(db_from_env)

  # Honor the 'X-Forwarded-Proto' header for request.is_secure()
  SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

  # Allow all host headers
  ALLOWED_HOSTS = ['*']

  # Static asset configuration
  import os
  BASE_DIR = os.path.dirname(os.path.abspath(__file__))
  STATIC_ROOT = 'staticfiles'
  STATIC_URL = '/static/'

  STATICFILES_DIRS = (
      os.path.join(BASE_DIR, 'static'),
  )

LOGIN TO HEROKU

  heroku login
  heroku create
  heroku config:set DISABLE_COLLECTSTATIC=1

PUSH to HEROKU

  $ git add .
  $ git commit -m "Herokuで動くようにした"
  $ git push heroku master

migration

  $ heroku run python manage.py migrate

run server

  $ heroku run python manage.py runserver