Chukwuemeka Aladimma
Acel's Blog

Acel's Blog

Deploying your Django App

Deploying your Django App

A step-by-step guide to move your Django app from development to production

Chukwuemeka Aladimma's photo
Chukwuemeka Aladimma
·Oct 27, 2021·

6 min read

Table of contents

  • Environment Variables
  • Gitignore
  • Debug and Allowed hosts
  • Secret Key
  • Databases
  • Static files
  • Gunicorn
  • Procfile
  • Runtime File
  • Requirements File
  • Git & Github
  • Short break
  • Django-Heroku
  • Heroku Deployment

In this article, I will be walking you through how you can deploy your django and DRF(Django Rest Framework) app. A little heads up, we'll be deploying our app on heroku but the steps are pretty similar with any other app hosting platform. Also, you should be familiar with git and Github/Gitlab.

Below is a list of steps to successfully deploy your django project:

  1. Environment Variables
  2. Gitignore
  3. Debug and allowed hosts
  4. Secrect key
  5. Static files
  6. Gunicorn
  7. Procfile
  8. Runtime file
  9. Requirements file
  10. Git & Github
  11. Django-Heroku
  12. Heroku deployment

First things first, we'll need to open our text editor and terminal. Now navigate to your project folder and activate your virtual environment. Let's begin!

NB: All single line code snippets are to be executed in your command line

Environment Variables

Before pushing our code to github, we don't want every single thing in our project leaving our PC. An example of such is the secret key for our app. To curb this we'll make use of a .env file to store all of our application's vital info.

pip install environs~=8.0.0

touch .env

Then in the settings.py file add

from environs import Env # new
env = Env() # new
env.read_env

Gitignore

We do not want git to track all our files like .env and our local database. To take care of that we make use of a .gitignore file.

touch .gitignore

Open .gitignore in your text editor and add the following files

.env
__pycache__/
db.sqlite3
.DS_Store # Mac only

Debug and Allowed hosts

It is vital that we set debug to false when moving to production and limit allowed hosts to prevent unauthorized access to our application.

In the settings.py file, update

DEBUG = env.bool(“DEBUG”, default=false)
ALLOWED_HOSTS = [‘.herokuapp.com’, ‘localhost’, ‘127.0.0.1’]

In the .env file add

export DEBUG=True

Secret Key

This is a very important info we don't want leaving our PC. Hence, we'll add it to our .env file

In the settings.py file you should see something like this

SECRET_KEY  =  '(-e%3z3yp5qsirfl6_+9=ko#!r6%0am8=^x9a))p2)3y-24g%*'

In the .env file add

export SECRET_KEY=(-e%3z3yp5qsirfl6_+9=ko#!r6%0am8=^x9a))p2)3y-24g%*

Notice that there's no quotation mark and space when adding it to the .env file. Also, each secret key is unique to a django project so don't expect this secret key to match with yours.

Now in the settings.py file, update

SECRET_KEY = env.str(“SECRET_KEY”)

Databases

We need to configure our database because while the default(sqlite3) is okay for local development, it's not sufficient for production. When deploying to Heroku, our app is automatically assigned a free PostgresSQL database. So we just need to configure our app to use sqlite3 locally.

In your settings.py file, update

DATABASES = {
"default": env.dj_db_url("DATABASE_URL")
}

Add this to the .env file

export DATABASE_URL=sqlite:///db.sqlite3

Then install the dj-database-url to utilize the DATABASE_URL environment variable to configure your Django application

pip install dj-database-url

Then we need to install Psycopg, a database adapter that lets our Python app talk to the PostgreSQL database.

pip install psycopg2-binary~=2.8.5

Static files

You can skip this if you're deploying a DRF app as it doesn't include any static file. If you're using django on the other hand, we have something extra to configure. We are doing this because django doesn't support serving static files in production itself

pip install whitenoise~=5.1.0

Then we need to add the configurations for whitenoise in our settings.py file

INSTALLED_APPS = [
...
'whitenoise.runserver_nostatic',         # new
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',             # new
...
]
STATIC_URL = '/static/'
STATICFILES_DIRS = [str(BASE_DIR.joinpath('static'))]         # new
STATIC_ROOT = str(BASE_DIR.joinpath('staticfiles'))            # new
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'     # new

Then make directories for our static files

#Run each line one by one in your command line/terminal
mkdir static
mkdir static/css
mkdir static/js
mkdir static/images

Then run the collectstatic command for the first time to compile all the static file directories and files into one self-contained unit suitable for deployment.

python manage.py collectstatic

As a final step, in order for our templates to display any static files, they must be loaded in. So add {% load static %} to the top of the base.html file.

{% load static %}
<html>

Gunicorn

We need to install gunicorn as the production web server

pip install gunicorn~=19.9.0

Procfile

This is tells heroku how to use our app.

touch Procfile

The configuration varies by app but this should do. Add the configuration below to your Procfile

release: python manage.py makemigrations bookgrid_app
release: python manage.py migrate

web: gunicorn bookgrid_proj.wsgi

Where ‘bookgrid_proj’ is the name of your django project and ‘bookgrid_app’ the name of your django app

Runtime File

This tells Heroku what version of Python to use for our app

touch runtime.txt

Open the file and paste the python version below. Or anyone most compatible with your app and heroku from this list

python-3.8.12

Requirements File

This lets heroku know what dependencies are needed for our app so it can be installed. First run pip freeze > requirments.txt to create a requirements.txt file that contains all our app's dependencies.

Git & Github

I'm assuming you're conversant with git and github by now. Just commit your latest changes and push it to your online repo on Github or Gitlab. If you don't know how to do that you can check out this article.

Short break

At this point we’ve done a lot but it's not over. You can take a break and continue later if you are stressed, it’s pretty normal the first time. If you’ve still got some juice left, let’s continue.

Django-Heroku

This is a Django library for Heroku applications that ensures a seamless deployment and development experience. It is very much needed if you are deploying your app on Heroku

To install the package run

pip install django-heroku

In your settings.py file, at the very bottom add

import django_heroku
django_heroku.settings(locals())

Heroku Deployment

You need to have an account with heroku. If you don't, create one here.

Login via the command line or terminal with

heroku login

Then create a new heroku app, where acel-app is the name you wish to give your app

heroku create acel-app

Now configure git so that when you push to Heroku, it goes to your new app name

heroku git:remote -a acel-app

Then create a PostgresSQL database on heroku for our app

heroku addons:create heroku-postgresql:hobby-dev

And manually add our environment variables except DEBUG and DATABASE_URL

heroku config:set SECRET_KEY='(-e%3z3yp5qsirfl6_+9=ko#!r6%0am8=^x9a))p2)3y-24g%*'

If we had other things in our .env file like email host or cloud storage configuration for images and videos, we’d have to manually add it to heroku as well

Screenshot from 2021-10-26 20-49-53.png

Using email host user and email host password in the screenshot above as an example

heroku config:set EMAIL_HOST_USER='mattew@gmail.com'
heroku config:set EMAIL_HOST_PASSWORD='yyuiuilo7tuy'

Now it’s time to push our code up to Heroku itself and start a web process so our Heroku dyno is running.

git push heroku main
heroku ps:scale web=1

The URL of your new app will be in the command line output or you can run heroku open to find it.

Now we need to migrate our PostgresSQL database and create a superuser

heroku run python manage.py makemigrations bookgrid_app
heroku run python manage.py migrate
heroku run python manage.py createsuperuser

AND WE ARE DONE AMIGOS!

Thanks for following to the end and I hope it was helpful.

¡Hasta luego!

 
Share this