How to deploy your Django Applications on Heroku

Moses Ogbopina
BitHubPH
Published in
7 min readOct 29, 2019
Photo by Tim Gouw from Pexels

Web application deployment has always been the phase of software development that web developers tend to dread, even though it’s something that shouldn’t be.

but why is that…

because an app that could be working perfectly fine on your local machine, when put a server suddenly decides to go through their teen rebellion phase and become stubborn and then stops being that little lovely app that was perfect on your local machine, and you find yourself dealing with issues like static assets management, database configuration and don’t even get me started on your media asset management.

Well all that ends now…(at least i hope it does), as we will be going through a step by step process in which we will build an app that you could reuse anytime you want to deploy your django application on heroku.

For this tutorial we will be using heroku, which is a platform as a service (paas) that we can use to deploy our django apps to the cloud.

There are some things we need to have ready on our system, i will be using a system running windows 10, if you are running another operating system some of the commands might be different, but you should still be able to follow with the tutorial. So ensure you have these before proceeding with the tutorial.

  • Python 3 installed (if you don’t you can do that here)
  • pipenv installed (see instructions here)
  • an heroku account (create one here)
  • git installed (install here)
  • download and install heroku cli tool (install here)

After you have done all the above listed, it’s time to login on the heroku cli (Note: this is done only once after installing heroku cli). Open up your git bash and type in the command heroku login you will be asked to input your heroku login credentials.

Now let’s create a folder for our django application and open our command prompt on that folder. Make sure you have pipenv installed, and type in

pipenv install django-heroku gunicorn

The above command will install django-heroku which will also install django, dj-database-url, whitenoise and psycopg2 and finally gunicorn will be installed, all in the virtual environment that will be created also.

Before we go any further let’s take a minute to talk about some of the packages we just installed.

  • django — because …duh
  • whitenoise — for simplified static file serving for Python web apps. (read more about whitenoise here)
  • dj-database-url — a simple Django utility that allows you to utilize the 12factor inspired DATABASE_URL environment variable to configure your Django application. (read more here)
  • gunicorn — a WSGI application server (read more here)

Let’s go ahead and create our django app. So go ahead and type the following code in your command prompt to create a new django project in the folder we created (Make sure you are in the virtual environment, if not type in pipenv shell to activate your virtual environment).

django-admin startproject <project_name> .

Now for the age old ritual of running your server and going to our browser to see that beautiful django rocket never takes off (Hope one day the django team will finally make that rocket take off)….

Run your development server using

python manage.py runserver

It’s time to configure our application for deployment.

Open up your project folder with your favorite text editor and locate the settings file inside of the root project directory, this is where the configuration will go down.

First let’s configure django_heroku to work with our application

  • At the top of our settings file we need to import django_heroku
import django_heroku
  • Next, at the very bottom of the file we need to have this
django_heroku.settings(locals())

Secondly let’s configure our static assets to use whitenoise.

  • Add whitenoise to the installed apps list right above the django.contrib.staticfiles app as follows
...
'whitenoise.runserver_nostatic',
'django.contrib.staticfiles',
...
  • Inside the MIDDLEWARE list in the settings file, add the following code right under the SecurityMiddleware.
...
'whitenoise.middleware.WhiteNoiseMiddleware',
...
  • At the bottom of the settings file, make sure you have the following variables defined
STATIC_URL = '/static/'STATIC_ROOT = os.path.join(BASE_DIR, 'static')STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

Up Next is our Database Configuration using dj-database-url

  • At the top of the settings file import dj-database-url as follows
import dj_database_url
  • Right under our DATABASE dictionary in the settings file, add the following code.
db_from_env = dj_database_url.config()DATABASES['default'].update(db_from_env)

Almost there …

Finally we need to create a file in the root directory of the project… and this file will be called Procfile with no extension, and the content of this file will be the code below.

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

Don’t forget to replace <project_name> with your project name. The above code is specifying what process heroku should run our application as, which is web in this case.

We can now go ahead to create our heroku app, so open up your git bash on your project folder and type in

heroku create <app_name> 

you can replace <app_name> with a name you desire for your app or you could just use heroku create and heroku will generate a wonderful name for you…(i must say i always look forward to this part … let’s see what i’ll get this time)

[Moses]: ~/Desktop/my_site$ heroku create
Creating app... done, intense-gorge-59251
https://intense-gorge-59251.herokuapp.com/ | https://git.heroku.com/intense-gorge-59251.git
[Moses]: ~/Desktop/my_site$

intense-gorge-59251 … boy that’s the stuff.

let’s go ahead and initialize git on our project directory

[Moses]: ~/Desktop/my_site$ git init
Initialized empty Git repository in C:/Users/Moses Ogbopina/Desktop/my_site/.git/

We need to add the remote heroku git repository for our application, and the git url can be found when we created the app.

[Moses]: ~/Desktop/my_site$ git remote add heroku https://git.heroku.com/intense-gorge-59251.git

we will have to add the url of our application to the ALLOWED_HOSTS list in our settings file.

ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'intense-gorge-59251.herokuapp.com']

next we need to git add and commit

[Moses]: ~/Desktop/my_site$ git add .
warning: LF will be replaced by CRLF in .vscode/settings.json.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in Pipfile.
The file will have its original line endings in your working directory
warning: LF will be replaced by CRLF in Pipfile.lock.
The file will have its original line endings in your working directory
[Moses]: ~/Desktop/my_site$ git commit -m 'initial commit'
[master (root-commit) 59f356b] initial commit
10 files changed, 292 insertions(+)
create mode 100644 .vscode/settings.json
create mode 100644 Pipfile
create mode 100644 Pipfile.lock
create mode 100644 Procfile
create mode 100644 db.sqlite3
create mode 100644 manage.py
create mode 100644 mysite/__init__.py
create mode 100644 mysite/settings.py
create mode 100644 mysite/urls.py
create mode 100644 mysite/wsgi.py

Finally you can go to your heroku application url and you should see the django welcome page.

For now our application is still using the default sqlite database, we need to change that in other to use postgresql, but before we do that let’s add our db.sqlite3 file to gitignore so it won’t be part of our subsequent commits.

Create a new file in the root directory of the project called .gitignore and the content of this file will be …

db.sqlite3

Since we have made some changes will need to add, commit and push. So open up your git bash and do the following

[Moses]: ~/Desktop/my_site$ git add .
[Moses]: ~/Desktop/my_site$ git commit -m 'added gitignore'
[master 333e35d] added gitignore
1 file changed, 1 insertion(+)
create mode 100644 .gitignore
[Moses]: ~/Desktop/my_site$ git push heroku master
Enumerating objects: 4, done.
Counting objects: 100% (4/4), done.
Delta compression using up to 4 threads
Compressing objects: 100% (2/2), done.
Writing objects: 100% (3/3), 282 bytes | 141.00 KiB/s, done.
Total 3 (delta 1), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote: Skipping installation, as Pipfile.lock hasn't changed since last deploy.
remote: -----> $ python manage.py collectstatic --noinput
remote: 119 static files copied to '/tmp/build_e1a9e9c0be3b0bb88801f674b6bae3e9/static', 377 post-processed.
remote:
remote: -----> Discovering process types
remote: Procfile declares types -> web
remote:
remote: -----> Compressing...
remote: Done: 67.7M
remote: -----> Launching...
remote: Released v7
remote: https://intense-gorge-59251.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/intense-gorge-59251.git
5a9a8e7..333e35d master -> master

Now we need to add postgres database to our app, still on your git bash type in the following command.

[Moses]: ~/Desktop/my_site$ heroku addons:create heroku-postgresql:hobby-dev
Creating heroku-postgresql:hobby-dev on intense-gorge-59251... free
Database has been created and is available
! This database is empty. If upgrading, you can transfer
! data from another database with pg:copy
Created postgresql-angular-29258 as HEROKU_POSTGRESQL_ROSE_URL
Use heroku addons:docs heroku-postgresql to view documentation

Now we can go ahead and migrate our database, so still on git bash

heroku run python manage.py migrate

Note that running just python manage.py migrate will migrate your local database. To run commands on your application on heroku, use the command

heruku run <command_goes_here>

You can now go ahead and create a superuser by running

[Moses]: ~/Desktop/my_site$ heroku run python manage.py createsuperuser
» Warning: heroku update available from 7.25.0 to 7.33.1.
Running python manage.py createsuperuser on intense-gorge-59251... starting, run.6767 (Free)
Running python manage.py createsuperuser on intense-gorge-59251... connecting, run.6767 (Free)
Running python manage.py createsuperuser on intense-gorge-59251... up, run.6767 (Free)
Username (leave blank to use 'u13061'): admin
admin
Email address: admin@email.com
admin@email.com
Password: **********

Password (again): **********

Superuser created successfully.

Now for the moment of truth… go to the admin section of your application on heroku and try loging in with your superuser credentials.

If you made it to this point, then congratulations you have successfully deployed your django application on heroku… Note there are other things that can still be done, but this is a very good starting point.

If you have found this helpful then don’t forget to exercise your fingers by seeing how many times you can click the clap button in 30 seconds.

--

--

Moses Ogbopina
BitHubPH

Python Developer | JavaScript Enthusiast | Certified Otaku