DEV Community

giftedstan
giftedstan

Posted on

Heroku: how to deploy a Django app with Postgres in 5 minutes!

how to deploy a Django app with Postgres

Heroku is the Platform as a Service (PaaS) platform that allows web developers to develop, create, run and manage their web applications completely on the cloud. To be provided as a service not just the hardware, but also the platform that seperates the hardware itself and allows you to enjoy the features that allow you to easilly carry out automatic balancing, deployment management and lots more.

If you do not already have an account with heroku, you can simply sign up now by going to heroku.com, it is entirely free to register and start using their services right away.

Deploying a Django Web Application on heroku is usually a difficult task to carry out as a beginner especially when your Django application has a backend and you want to use the heroku postgres as your cloud database.

Python Image

In my early days building and hosting django projects on heroku, i really spent several hours reading online how to host a django project with postgres on heroku because there was no detailed article on how to do that. This post is step by step guide to on how i learnt to deploy Django apps on heroku easily using postgres as backend.

STEP 1: Create a Django app ( This is if you haven’t already created it).

STEP 2 : Download and Install the Heroku Command Line Interface.

STEP 3 : Open up your main project folder in the terminal. Create and activate a new virtual environment (this is if you dont already use a seperate virtual environment for this your project that you want to host.

cd main_project_folder
virtualenv venv
source venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

STEP 4: Install the dependencies and these packages that are required by your django app.

pip install django gunicorn whitenoise dj-database-url psycopg2
Enter fullscreen mode Exit fullscreen mode

STEP 5 : Create a file named Procfile and add the following line below to it.

web: gunicorn nameOfProject.wsgi --log-file -
Enter fullscreen mode Exit fullscreen mode

Here nameOfProject is name of folder which includes

settings.py 
Enter fullscreen mode Exit fullscreen mode

Heroku apps makes use of a file named Procfile with no extensions that declares the commands that are executed by the application on the applications startup. For more information about Heroku Procfile, refer → Here

STEP 6 : Create a requirements file requirements.txt

This requirements file will hold all the modules that you made use in your app for proper functioning and yeah you do not have to manually write down every module that you used, there's a command for that and its right below.

pip freeze > requirements.txt 
Enter fullscreen mode Exit fullscreen mode

STEP 7 : Create a runtime file
Use the command below to create a runtime text file in your projects root folder

touch runtime.txt
Enter fullscreen mode Exit fullscreen mode

then, add the following python-3.6.7 or any other python runtime supported by heroku.

Django Developer

STEP 8 : Initialize a git repository in your application root folder(if you have not already done that). Also add and save the changes you made to git.

git init
Enter fullscreen mode Exit fullscreen mode

Add all the changes to git by running

git add .
Enter fullscreen mode Exit fullscreen mode

and commit the changes them by

git commit -m "message" 
Enter fullscreen mode Exit fullscreen mode

STEP 9 : Login to Heroku terminal by running

heroku login
Enter fullscreen mode Exit fullscreen mode

Next create your heroku application by running

heroku create
Enter fullscreen mode Exit fullscreen mode

If you wants to use a custom name other than the generated name that is usually out of context, run the following commands instead

heroku create nameofapp
Enter fullscreen mode Exit fullscreen mode

STEP 10 : Now let us modify the settings.py file a bit.

Modify allowed hosts by adding thenameofyourapp.herokuapp.com

ALLOWED_HOSTS = ['0.0.0.0', 'localhost', '127.0.0.1', 'nameofapp.herokuapp.com']
Enter fullscreen mode Exit fullscreen mode

You can also use

ALLOWED_HOSTS = ['*',]
Enter fullscreen mode Exit fullscreen mode

Next, Set

DEBUG = False
Enter fullscreen mode Exit fullscreen mode

this is done you could use heroku logs for debugging and your application would show an error page instead of showing your application errors in production.

Modify the INSTALLED_APPS in the settings by adding

whitenoise.runserver_nostatic
Enter fullscreen mode Exit fullscreen mode

also the MIDDLEWARE settings by adding

'whitenoise.middleware.WhiteNoiseMiddleware',
Enter fullscreen mode Exit fullscreen mode

next add the following

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
Enter fullscreen mode Exit fullscreen mode

Add

import dj_database_url
Enter fullscreen mode Exit fullscreen mode

at the top. After the DATABASES section
add

db_from_env = dj_database_url.config(conn_max_age=600)
DATABASES['default'].update(db_from_env)
Enter fullscreen mode Exit fullscreen mode

Also make sure that your settings file has the following variables set STATIC_URL, STATIC_ROOT , STATICFILES_DIRS accordingly.

Also make sure that the media file variables is set.

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/'
Enter fullscreen mode Exit fullscreen mode

Commit the changes and save them in git by running

git add .
Enter fullscreen mode Exit fullscreen mode

and

git commit -m "change settings"
Enter fullscreen mode Exit fullscreen mode

STEP 11: Adding and configuring Postgres ( this was a challenge to me then...lol)

The following commands would create postgresql database on heroku for you app and fetch the database url.

heroku addons:create heroku-postgresql:hobby-dev
heroku config -s | grep DATABASE_URL
Enter fullscreen mode Exit fullscreen mode

You can also run

heroku pg:info
Enter fullscreen mode Exit fullscreen mode

to get the details of your database on heroku.

Add-on
Enter fullscreen mode Exit fullscreen mode

will give you nameOfHerokuDB .
Now You can also push your local Postgres database to herokuDB by running

push local database:PGUSER=postgres PGPASSWORD=password  heroku pg:push postgres://name_of_host/name_of_local_database nameOfHerokuDB
Enter fullscreen mode Exit fullscreen mode

For example

PGUSER=postgres PGPASSWORD=mydemopassword heroku pg:push postgres://localhost/myDB  postgresql-convex-12345
Enter fullscreen mode Exit fullscreen mode

**STEP 12 : Disable the default heroku Collectstatic command and push the files to heroku.

Heres something i do, to avoid the heroku static files issues, i run the following commands bellow

python manage.py collectstatic
Enter fullscreen mode Exit fullscreen mode

then i add and commit to git, next i run

heroku config:set DISABLE_COLLECTSTATIC=1
git push heroku master
Enter fullscreen mode Exit fullscreen mode

You can open your deployed application by running

heroku open
Enter fullscreen mode Exit fullscreen mode

Possible Errors

  • If you have not already set static root in your Django settings, you will get a DISABLECOLLECTSTATIC error.
  • Django does not serve static files in the application's server on it's own, that is why why we have to define a place where heroku can keep and manage all the static files.
  • Simply add STATIC_ROOT in your settings.py file. After making all the necesssary changes, make a commit and try pushing with
git push heroku master
Enter fullscreen mode Exit fullscreen mode

again.

It's Deployed!

Congratulations. If you encounter error during the push command which usually comes if you are doing it for the first time, do not freak out, a solution is around the corner, you can simply comment your issue bellow or you can search on Stackoverflow.

Discussion (0)