How to deploy Django to Heroku

Introduction:

Most of you would’ve already seen n number of blogs on how to deploy Django projects to Heroku but in this article, I shall explain in simple words in a sequential manner without much confusion.

We shall consider a simple project without any additional boiler plate code. I shall call the project as mysite and app as appOne.

I shall start from scratch and attach this repository at the end of this tutorial.

For Linux Users:

python3 -m venv Environ
source Environ/bin/activate
python -m pip install django

For Windows Users:

python -m venv Environ
cd Environ/Scripts/
activate
cd ../../

Configuring Django

Continuing this:

django-admin startproject mysite
cd mysite
django-admin startapp appOne

This is how your tree will look after running those commands successfully :

mysite
    │   manage.py
    ├───appOne
    │   │   admin.py
    │   │   apps.py
    │   │   models.py
    │   │   tests.py
    │   │   views.py
    │   │   __init__.py
    │   │
    │   └───migrations
    │           __init__.py
    └───mysite
            asgi.py
            settings.py
            urls.py
            wsgi.py
            __init__.py

Steps to launch and deploy the project to Heroku:

Step One:

from pathlib import Path
import os

BASE_DIR = Path(__file__).resolve().parent.parent
SECRET_KEY = os.environ.get('SECRET_KEY')
DEBUG = os.environ.get('DEBUG')
ALLOWED_HOSTS = []

Once you've created the Django project, please add the security key to your Environment secrets and Config Vars.

Step Two:

We don’t have any static files for this project, but if needed you can use whitenoise.

MIDDLEWARE  = [
   'whitenoise.middleware.WhiteNoiseMiddleware',
]

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

In config vars set DEBUG_COLLECTSTATIC = 1.

Step Three:

After configuring the project, we'll now be freezing the requirements and Procfile

pip freeze>requirements.txt
Procfile:
web: manage.py makemigrations && manage.py migrate
web: gunicorn mysite.wsgi:app

Step Four:

Commit all these files to your git repository and push it to your source .
I’ll be using GitHub for this tutorial

git init . 
git add . 
git commit -m  “Initial Commit🚀”
git remote add origin <link>
git push -u origin master

Step Five:

Go to dashboard and deploy

It should be working fine! Feel free to reach out if there are any issues.

29