Deploying Django App To Heroku (1)
By: Samuel Damilare
Tags: Deployment, Heroku, Django

Simple steps to deploy your django app to Heroku

Hello and welcome to my blog. Today, I am going to explain how to deploy a simple django app to heroku.

Heroku is a web host platform (PaaS) that allows deployment of apps from your local server to the public. They have a free plan and a paid plan. Of course, the free tier is limited to five apps, one dynos and other things which are available in the paid plan.

Enough of the talks and let’s get straight down to business. I assume you have you django app working perfectly in your machine. I mean if you go to your virtual environment, activate it and run python manage.py runserver, the server runs at localhost:8000 and the app displays on your browser. The very first thing you’ll need to do is to create an heroku and a github account if you don’t have one. You can do that here https://signup.heroku.com/ and create a github account here https://github.com/join. If you’re done, You may continue the journey.

Step 1: Download the Heroku Toolbelt

To streamline the deployment process, heroku provides a toolbelt which ease the processes. Click this link https://devcenter.heroku.com/articles/heroku-cli to download it and install for your Machine’s OS. After installing, you may proceed. To check if it installed successfully, run the following command in your terminal. If a version number comes up, good ! otherwise, you need to try the installation again.

$ heroku -v

Step 2: Setting up Git

You only need to do this once per project. For a new project, you’ll initialise another git process. There’s something you need to install. It’s the heroku toolbelt which will help streamline the processes between heroku and your project deployment.

$ git config --global user.name "Your Github Name"

$ git config --global user.email "you@youremailaddress.com"

$ git config --global push.default matching

$ git config --global alias.co checkout

$ git init

After running the above commands, git would be initialised in your virtual environment. Simple right ? Now it’s time to upload our project and files to heroku. Run the following commands.

$ git add .

$ git commit -m 'initial commit'

$ git push heroku master

Step 3: Create SSH Keys

To connect to heroku via your terminal, you will need to create ssh keys. Run the commands below to do this. This is for Mac OS. For windows, ubuntu and other OS, you can easily find how to do this (generate ssh keys) via google.

$ mkdir ~/.ssh

$ cd ~/.ssh

$ ssh-keygen -t rsa

The above commands create a hidden directory ‘ssh’ and generate a public/private rsa key pair there. This key will be used later in the deployment. Click enter to save it in the current directory, when asked for password, you can leave it blank or put a password. You will need to navigate back to your project directory after this.

Step 4: Heroku Login

You are getting closer to the finishing line in just a bit. You need to login to heroku to start your deployment process. This will be done from your terminal. Remember the heroku toolbet you downloaded ? This is where it becomes useful as all things will be done from your terminal. Run the command below.

$ heroku login

Follow the instruction (any click except q) from your terminal to login. A browser window will pop up alerting you to click login. After that, you’ll be logged in to your heroku account from your terminal. Isn’t that wonderful ? Most of your operations will be done from here. Feeling like a DevOp engineer right :) I know that feeling. Go back to your terminal and you’ll see you’ve been logged in successfully with your email address showing.

Note: For the free plan, you might want to fill your credit card details to allow a domain name. Don’t worry, you won’t be debited as long as you remain in the free plan.

Run the following commands to proceed.

$ heroku keys:add

I guess you know what this does. The above command will upload the ssh keys to heroku. Now you’re almost there but there are some dependencies needed by heroku from our app. You’ll need to download them.

Step 5: Setup Dependencies

Heroku will check your django app to see if these dependencies exist. Usually, they’re in a requirements.txt file and a Procfile. If they don’t exist, your deployment will fail. Follow the commands below to setup theses dependencies.

$ touch Procfile

This create a Procfile in your project directory. Type web: gunicorn yourprojectname.wsgi and save it. Gunicorn is simply a Web Server Gateway Interface (WSGI) server implementation that is commonly used to run Python web applications. You can click here https://gunicorn.org/ to get more info on it.

Go to your settings.py file and type the following at the top just after import os.

import os # heroku imports

import django_heroku

from decouple import config

import dj_database_url

...

For each of these, you’ll need to pip install them.

$ pip install django-heroku

$ pip install python-decouple

$ pip install gunicorn

You might encounter an error here with the first pip. This is because postgres isn’t installed. Solution is to install postgres on your machine.

If you have postgres installed and you still encounter an error when trying to download psycopg2, say Error: pg_config executable not found. It simply means that your pg_config path isn’t found. To solve this error, run the command (recall, this is for mac os users) to find the path

$ sudo find / -name "pg_config" -print

This shows the path of the pg_config. Then run

$ export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/9.5/bin

This will export the path of the pg_config file and make it accessible to install psycopg2. Now try to pip install django-heroku again and the rest. After completing the pip installation, run

$ pip freeze

This shows you all the installed dependencies needed by heroku for your deployment.

dj-database-url==0.5.0 Django==2.2.2 django-crispy-forms==1.7.2 django-heroku==0.3.1 gunicorn==19.9.0 Pillow==7.1.1 psycopg2==2.8.6 python-decouple==3.3 pytz==2019.1 sqlparse==0.3.0 whitenoise==5.2.0

You should have the above. If not, try repeating the process again. Then to create the requirements.txt file, run

pip freeze > requirements.txt

You will observe a new file in your project directory called requirements.txt. This file contains all the dependencies needed by heroku for the successful deployment of our django app. We’re almost done !

You now need to tell your django app about these dependencies. Do this by typing in your middleware in the settings.py file

MIDDLEWARE = [

'django.middleware.security.SecurityMiddleware',

'whitenoise.middleware.WhiteNoiseMiddleware',

...

]

Then add to the bottom of the settings file

... STATICFILES_DIRS = BASE_DIR / "static", # Configure Django App for Heroku.

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' django_heroku.settings(locals())



Note: This is for django 2.2.2. For newer versions, check https://docs.djangoproject.com/en/3.1/howto/static-files/ to know how to add static files.

Woah !!!

That was a long one. We’re almost there now.

Step 6: Create Heroku App

So now, run the following commands.

$ git add .

$ git commit -am 'setup heroku dependencies'

$ heroku create yourappname

Note: If you don’t add a name, heroku will generate a random name for you.

You will see something like this.

Creating ⬢ appname... done https://yourappname.herokuapp.com/ | https://git.heroku.com/yourappname.git

If you do, congratulations, your app has been successfully deployed. You can copy the url and open on your browser…

But wait ! Didn’t you say successfully deployed ? But my app isn’t showing. Yes, it won’t show yet but you should see a Heroku | Welcome to your new app! message. If yes, you’re with me and are on the right track. Let’s proceed.

Step 7: Push Codes To Heroku

Your app isn’t showing yet because you haven’t pushed your codes there. All along, you’ve been setting up all the dependencies and requirements to make this step an easy one.

Proceed with the following command and watch how your codes are uploaded to heroku with the dependencies. Depending on how large your app is, the upload time varies.