How to deploy Django on Heroku

Make sure requirements.txt is in the root of your project folder.

Add these to your requirements.txt:

dj-database-url==0.3.0
dj-static==0.0.6
static==1.1.1

Add a Procfile in the root of your project with this content:

web: gunicorn <project_name>.wsgi --log-file -

In case you use a src folder you can CD into it like so:

web: sh -c 'cd src/ && gunicorn <project_name>.wsgi --log-file -'

Add this to your settings.py file:

import dj_database_url

DATABASES['default'] = dj_database_url.config()

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

Change your wsgi.py content to this:

from django.core.wsgi import get_wsgi_application
from dj_static import Cling


application = Cling(get_wsgi_application())

Add a runtime.txt file in the project root with this content:

python-2.7.9

Now initiatie the project like so:

$ heroku create

Then push the first commit like so:

$ git push heroku master

You can open your app like so:

$ heroku open

Viewing the logs live:

$ heroku logs --tail

To rename the auto-generated name to something more clear, do:

 Login to heroku.com and change the app-name to something with small letters and dashses. e.g. example1-production.

 $ git remote rm heroku
 $ heroku git:remote -a example1-production

Running management commands:

$ heroku run python manage.py migrate

Or for more control do, but remember changes made here are not visible in your dyno. Hence, local_settings.py woudn't make sense:

$ heroku run bash


For settings use the environment variables in your settings.py:

import os

def get_env_variable(var_name):
    """ Get the environment variable or return exception """
    try:
        return os.environ[var_name]
    except KeyError:
        pass


SECRET_KEY = get_env_variable('SECRET_KEY')
ALLOWED_HOSTS = ['*', ]
RAVEN_CONFIG = {
    'dsn': get_env_variable('SENTRY_URL'),
}


To view the current environment variables:

$ heroku config

To set a config variable:

$ heroku config:set TIMES=2

And to make it actually work:

$ heroku ps:scale web=1