Deploying Django to production (on Heroku)

This is how you deploy your Django application on Heroku. Just five easy steps and your application is online ready for production. Django uses SQLite database by default so we use it too here!

Step 1 – Initial settings.py configuration

In settings.py comment out the original SECRET_KEY configuration and add below it the following code:

SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'your_key_from_the_code_you_commented')

Replace the your_key_from_the_code_you_commented with the key from the code you have just commented out.

In settings.py comment out the original DEBUG configuration and add below it the following code:

DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) )

Step 2 – Creating an application repository on Github

Visit http://github.com and create a free account if you don’t have one.
Create a new repository:

  • Name the repository as you wish (e.g. myrep1)
  • Fill the description field (e.g. The repository for my Django application)
  • The Add.gitignore selection list → choose Python
  • The Add license selection list → choose as desired
  • Check Initialize this repository with a README
  • Press Create Repository button
  • Click the green Clone or download button on your new repository page and copy the URL (we are going to paste it soon)

Step 3 – Clone the repository on your local computer

Visit https://git-scm.com/downloads and install git for your operating system.

Open the terminal and clone your repository by running the following command:

git clone https://github.com/<your_git_user_id>/name_of_your_repository.git

The https://github.com/<your_git_user_id>/name_of_your_repository.git is the link you copied at the end of step 2.

Navigate into the new repository folder.

cd name_of_your_repository

Copy all your project folders and files into the new repository folder.

Open .gitignore file and place the following lines of code at the bottom of it.

# Text backup files
*.bak

#Database
*.sqlite3

Add all files to git by running the following command in the terminal:

git add -A

Check all files that you are about to add.

> git status

Commit the files to your local repository.

git commit -m "My first commit"

Synchronize the local repository with Github repository.

git push origin master

Go to the Github website, refresh the repository page and check if all of the project folders and files are there.

Step 4 – Preparing the application for Heroku

In the root of your local GitHub repository create a file and name it Procfile (with no extension).
Copy the following text into it:

web: gunicorn name_of_your_rootfolder.wsgi --log-file -

Install Gunicorn locally using pip in the terminal by running the following command:

pip3 install gunicorn

Install dj-database-url locally

pip3 install dj-database-url

Open settings.py and copy the following code at the bottom of it.

# Heroku: Update database configuration from $DATABASE_URL.
import dj_database_url
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

Below the code you just paste at the bottom of the settings.py file copy the following code which is related to static file that will be served in production environment:

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/

# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# The URL to use when referring to static files (where they will be served from)
STATIC_URL = '/static/'

Install Whitenoise locally via the terminal:

pip3 install whitenoise

In the settings.py file, at the MIDDLEWARE setting and add the WhiteNoiseMiddleware below the SecurityMiddleware (it is the second line shown in the code below: 'whitenoise.middleware.WhiteNoiseMiddleware',).

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

Add the following at the bottom of your settings.py file:

# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Create the requirements.txt file locally in the repository folder.

pip3 freeze > requirements.txt

According to this tutorial your the requirements.txt file should look like shown below:

dj-database-url==0.4.1
Django==1.10.2
gunicorn==19.6.0
psycopg2==2.6.2
whitenoise==3.2.2

Everything else should be deleted, unless you added them!

Create the runtime.txt file locally in the repository folder and add the following text:

python-3.5.2

Save changes to Github and re-test by running the following code (one line at a time):

git add -A
git commit -m "Prepared for deployment to heroku"
git push origin master

Re-test the site locally to make sure it wasn’t affected by any changes we have made.

python3 manage.py runserver

Visit http://localhost:8000 and make sure everything works properly within the application.

Step 5 – Deploying on Heroku

Create a Heroku account.
Login and go to the dashboard.
Install Heroku client for you operating system (more details at https://devcenter.heroku.com/articles/getting-started-with-python#set-up).
Check if the client is correctly installed by running the following command in the terminal:

heroku help

Create and upload the web application.

heroku create

If you specify a value after create then that will be the name of your application. See example below:

heroku create dandumitracheapp

Push the app to Heroku repository.

git push heroku master

Perform a migrate operation.

heroku run python manage.py migrate

Create superuser so you can accesss the admin interface.

heroku run python manage.py createsuperuser

Take a look at your web application in the browser.

heroku open

Leave a Reply