Deploy Django to Heroku using postgress database 2022
This article tries to solve all the problems you might encounter while deploying django using postgressql on heroku in 2022
This article is stemmed from the issue I encountered trying to deploy a django project on heroku using postgress. Hence, I would try to be direct so as to prevent any pitfalls you may encounter while building your own project.
This article assumes you already know about django. If you are not very conversant with django, you can checkout the documentation. So without wasting much of your time, let’s get started 💪.
Packages required are:
- Django
- gunicorn
- whitenoise
- django database url
- pyscopg2
- python-dotenv
Disclaimer: I would be making use of a linux terminal with shell commands but these commands can be replicated on any other operating systems.
Step 1: Setup django project
Create a new directory
Lets call this foldermy_project
, the command below shows how to make a directory using terminal
$ mkdir my_project
Create a virtual environment
Use pip install venv
if you dont have virtual env installed on your system. create and activate the virtual environment using the command below. The environment is called env
$ cd my_project
$ python3 -m venv env
$ source env/bin/activate
Install Packages
Install all the packages listed above. You can do this with one command as shown below
$ python3 pip install django gunicorn whitenoise dj-database-url psycopg2 python-dotenv
Create Django Project
Create a django project in the current directory using the django start project command. The base directory for this project is named core
this is to avoid conflict with the project name. Dont forget the .
after the core, this tells django to create the project in the current directory
$ python3 -m django startproject core .
So, great work! you have your django project setup successfully. You can test this project using the command
python3 manage.py runserver
I would not focus on creating templates in django because this article focuses on deployment and setting up. You can read more on creating templates in django from the official documentation.
Step 2: Prepare Project for Deployment
Project requirements
Freeze project requirements using the command in the terminal
pip freeze > requirements.txt
This creates a requirements.txt
file with all the project requirements.
Setup static files
create a folder called static
in the my_project
directory this is the folder containing your css and js files.
In the settings.py
file under the INSTALLED_APPS
list add the whitenoise static settings
'whitenoise.runserver_nostatic',
Add whitenoise middleware to the settings.py
file under MIDDLEWARE
and add the following code immediately after the django.middleware.security.SecurityMiddleware
whitenoise.middleware.Whitenoise.Middleware
add the static files configurations under the STATIC_URL='static/'
STATIC_ROOT = BASE_DIR/'static'
STATICFILES_STORAGE='django.contrib.staticfiles.storage.StaticFilesStorage'
Configure the Database
After the DATABASES
in the settings.py
file, add the following code.
if "DATABASE_URL" in os.environ:
DATABASES['default']=dj_database_url.config(
conn_max_age=600, ssl_require=True)
This script checks if the DATABASE_URL
variable exists in the environment variable and then uses the database url to source the databse.
import all packages at the top of the settings.py
and load all environment variables using the load_dotenv()
command.
import dj_database_url
import os
from dotenv import load_dotenvload_dotenv()
Set Allowed Hosts
in the settings.py
file, under the ALLOWED_HOSTS
add the hosts for your app
ALLOWED_HOSTS = [
'127.0.0.1',
'*.herokuapp.com'
]
Set Environment variables
Create a .env
file in the my_project
folder. Copy the SECRET_KEY
from the settings.py file and add it to the env file. The content of the .env
file is as follows
SECRET_KEY= your_secret_key
DEBUG = True
replace the secret key in the settings.py
file with the code below
SECRET_KEY= os.getenv('SECRET_KEY')
replace the DEBUG
key with the code below
DEBUG=(os.getenv('SECRET_KEY', 'True') == 'True')
Step 3: Setup For Heroku
Create Heroku app
Login to the heroku dashboard and create a new app
Use a unique name and create a new app in any region of your choice. It is recommended that you choose a region close to you.
Note: don’t upgrade your heroku stack to
heroku 22
this would cause errors with build
Create Runtime
in the my_project
folder create a runtime.txt
file and in the file add
python-3.8.13
This is the latest version supported on heroku 20
and this would work well for all latest version of django (as of the time of writing this article)
Create Procfile
in the my_project
folder, create a file called Procfile
and in the file add
web: gunicorn my_project.wsgi --logfile -
The Procfile is the entry point for heroku for your django application
Add Configurations on Heroku
navigate to the heroku app under the settings tab, look for the Reveal Config Vars
button and add the following configurations
DISABLE_COLLECTSTATIC = 1
SECRET_KEY = put_your_django_secret_key_here
Add Postgress Database
In the heroku Resources
tab, click on Find more add-ons
select the Heroku Postgres
This is a free ad-on that provides storage up untill the specified limit.
Very Important Step
Make sure you run migrations on the postgress database before deploying the app. You can do this by
- go to heroku
settings
tab and in theReveal Config Vars
copy the value for theDATABASE_URL
key - in the
.env
file addDATABASE_URL
and paste the key you copied here - run
python3 manage.py migrate
to add the tables to the postgress database - You can now remove the
DATABASE_URL
key from the.env
file
Note: This step is necessary to build the database table that would be used to write data onto the postgres database.
I had to figure this out myself, so… you’re welcome 😊.
Step 4: deploy to heroku
Note: There are different methods to deploy your application to heroku, but I prefer using github because it is less prone to errors and doesn’t require install ation of the Heroku CLI. It also alows you to keep you application up to date with all latest changes
Send Folder To Github
- Initialize your current directory —
my_project
— usinggit init
- create your
.gitignore
file in themy_project
folder - add the following code in the gitignore file
.env
env/
*__pycache__/
*migrations/
db.sqlite3env/
5. Create a repository on github
6. push your files to github using git push
.
Link project to heroku
- On heroku, go to the
Actions
tab and - Click on the
Connect to Github
button - Give Heroku permission to access github and .
- Select the repository where you have your project
Final Step
You should see your project live and active. Find the link to your project in heroku under the settings
tab. It is listed under the Domains.
Summary
Checkout my github project which uses django for deployment. Feel free to copy the settings file for your project. Dont forget to follow me on github and star the repository— it would be really appreciated.
db.sqlite3
4. Add all files to git using git add .
Checkout my github project which uses django for deployment. Feel free to copy the settings file for your project. Dont forget to follow me on github and star the repository— it would be really appreciated.
So there you have it 😃. This was a long article but it sure is worth the time . happy coding 💻…
if you found this helpful, follow me on medium for more helpful content.