In this example we will deploy a test environment of the app "myproject".
Install virtualenvwrapper:
pip install virtualenvwrapper
Create a virtual environment for your app. Henceforth, everything assumes you are inside the activated virtualenv.
Heroku toolbelt for deployment:
Use heroku way of declaring database settings with dj-database-url:
pip install dj-database-url
PostgreSQL python adapter:
pip install psycopg2
Gunicorn:
pip install gunicorn
Create Procfile to launch webserver:
web: python manage.py run_gunicorn -b "0.0.0.0:$PORT" -w 3
Install honcho (python port of foreman) for local management of Procfile and .env files:
pip install honcho
Create your .env file and populate it with minimum settings:
DEBUG=True SECRET_KEY='phzr0^(oamc0^50jn82j-g$rrrlq+td8b4h%0==wc=r^-2qrdu' DATABASE_URL=postgres://pguser:pgpassword@localhost:5432/dbname
Use honcho to run usual python manage.py... commands:
honcho run python manage.py ...
Use honcho to start the server in your local environment, using the local environment variables in .env file:
honcho start
Use this function to map string-version booleans to proper code booleans:
def env_var(key, default=None):
"""Retrieves env vars and makes Python boolean replacements"""
val = os.environ.get(key, default)
if val == 'True':
val = True
elif val == 'False':
val = False
return val
Add gunicorn to INSTALLED_APPS:
INSTALLED_APPS = (
...
'gunicorn',
...
)
Get your databse url from the env var and assign it to DATABASES:
import dj_database_url
DATABASES = {'default': dj_database_url.config(default=env_var('DATABASE_URL'))}
Gunicorn seems to need LOGGING on Heroku, so make sure you have some stuff there:
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Create new heroku app:
heroku apps:create myproject-test --remote test
Push git repo:
git push test master
Add env vars:
heroku config:add DEBUG=True heroku config:add SECRET_KEY='n=&1@3s@0ma&8ienk&&w6#n6*duzzx16pk)_3qyi-9e$sq*cq+' ...
OR push your local .env file to heroku::
heroku config:push
Initialize database:
heroku run python manage.py syncdb --noinput
Run migrations:
heroku run python manage.py migrate --all
Collect static:
heroku run python manage.py collectstatic --noinput
Create superuser for admin:
heroku run python manage.py createsuperuser
Scale web dyno:
heroku ps:scale web=1
Add backups addon:
heroku addons:add pgbackups
Add user-env-compile to enable automatic collectstatic to S3 (see http://devcenter.heroku.com/articles/labs-user-env-compile):
heroku labs:enable user-env-compile