Deploy your Django + PostgreSQL web-application on heroku with environment variables.

Deploy your Django + PostgreSQL web-application on heroku with environment variables.

In this article, we're going to see how to deploy your Django + PostgreSQL web-application on Heroku. We will also be seeing how to set up environment variables in Heroku for our database credentials.

a.jpg About Heroku:

Heroku is a container-based cloud Platform as a Service (PaaS). Developers use Heroku to deploy, manage, and scale modern apps. It is elegant, flexible, and easy to use, offering developers the simplest path to getting their apps to market.

CONFIGURE OUR DJANGO APP FOR HEROKU DEPLOYMENT:

Let's install the necessary dependencies (in your case, you might be having your existing dependencies installed, the following dependencies are for our deployment):

> pip install psycopg2
> pip install django-environ
> pip install gunicorn
> pip install django-heroku

Let's add Postgres configuration in your settings.py as follows (make sure that you include the .env file in .gitignore ):

import os
import environ

env = environ.Env()
# reading .env file
environ.Env.read_env()
#...
#...rest will be same

'''we will set all these environment variables in heroku dashboard later on'''
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': env('POSTGRES_DB_NAME'),
        'USER': env('POSTGRES_USER'),
        'PASSWORD': env('POSTGRES_PASSWORD'),
        'HOST': env('POSTGRES_HOST'),
        'PORT': env('POSTGRES_PORT'),
    }
}

#...

'''
As we are using Django, the collectstatic command also runs automatically 
during the deployment process 
so, for that we have to include STATIC_ROOT and STATIC_URL
'''
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATIC_URL = '/static/'

#...rest will be same

Let's add requirements.txt in our project directory by running the following command:

pip freeze > requirements.txt

it has to be 'requirements.txt'

If you are using pipenv as your virtual environment run following command to add requirements.txt:

pipenv lock -r > requirements.txt

Why requirements.txt?

When you deploy to Heroku, the dependencies you specify in your requirements. txt file are automatically installed before app startup.

Now, create Procfile and runtime.txt in your project directory as follows:

her1.PNG

Add following configuration in Procfile:

web: gunicorn <your_project_name>.wsgi:application --log-file - --log-level debug
python manage.py collectstatic --noinput
manage.py migrate

Here, "your_project_name" means the folder which holds settings.py. In my case, it's ToDoapp.

A Procfile is a file in your project's root directory that tells Heroku how your app should start and run. In the Procfile, we'll tell Heroku to start a Gunicorn server and then point that server to our Django project's default WSGI interface that exists in your project folder, in the same folder where your settings.py file exist.

Add following line in runtime.txt:

python-3.7.9

runtime.txt file tell heroku the exact python version number to use to run our application. In my case, I want to use Python version 3.7.9 (I would suggest you to mention same version as mine)

Create a new GitHub repository to hold our project:

ger02.png

Now, let's push our project to GitHub by running the following commands (make sure you have git installed in your machine)

> git init
> git add .
> git commit -m "first commit"
> git remote add origin <your repository url>.git
> git push -u origin master

Now, we have our project ready on github with necessary files with configuration.

LET'S DEPLOY OUR PROJECT ON HEROKU:

If you don't have Heroku account, go to signup.heroku.com and Sign Up there.

CREATE A NEW APP:

As soon as you sign in, you will be redirected to the following page:

file01.PNG click on "Create new app"

Give your app a name and keep the region default (United Stated) and click on Create app as follows:

her3.PNG

Now go ahead and connect your GitHub account to the Heroku by selecting GitHub from Deployment method in the Deploy tab on your Heroku dashboard as follows:

her4.PNG Give the necessary permissions and you should see something like this:

her5.PNG After connecting your GitHub account, search for the repository where you have uploaded your project and hit "connect".

Now, scroll a little bit and your should see following page:

her03.PNG Click on "Enable Automatic Deploy" which will enable the deployment as soon as you push your code to the connected GitHub repository in future.

As this is our first deployment we need to deploy manually. So, go ahead and hit "Deploy Branch" as shown in above image and it should start the deployment process.

Don't panic, yes it will crash our application as we haven't added our database and we also haven't configured our environment variables. So, let's do that.

LET'S ADD POSTGRESQL DB INSTANCE FOR OUR APPLICATION:

Go to Resources and search for "Heroku Postgres" as follows:

her04.PNG

After selecting, it will pop up one window, go ahead and click on "Submit Order Form" it will attach a Postgresql DB instance for our application.

Now, click on "Heroku Postgres" which is below search bar. It should redirect you to the Database page. That means we have successfully created a PostgreSQL DB for our application.

Click on Settings -> View Credentials... as shown below:

herd1.PNG

herd2.PNG

These are the credentials of your Postgres DB. We have to add these credentials in our Config vars so keep them saved somewhere locally.

LET'S ADD THESE DB CREDENTIALS IN CONFIG VARS AS OUR ENVIRONMENT VARIABLES:

Go back to the page where we have deployed our application and go to Settings -> Config Vars and click on "Reveal Config Vars" (Config vars are nothing but our environment variables) as follows:

her7.PNG

Now, go ahead and add the Database credentials in Config Vars as follows:

hercrd.PNG Now go to Deploy -> Manual Deploy and hit "Deploy Branch" as follows:

her03b.png

After deploying you should see following in Activity tab of your heroku app dashboard:

act.PNG

Now, we have to add our domain name in ALLOWED_HOSTS so let's do that:

Go to your settings.py and add your domain name in allowed hosts as follows:

# in my case its djangotodo-list.herokuapp.com
# in your case it should be 'your_app_name.heroku.com'
ALLOWED_HOSTS = ['djangotodo-list.herokuapp.com']

As we've changed our settings.py we have to push our code again to our GitHub repository. So, let's do that by running following commands:

> git add .
> git commit -m "added domain name in ALLOWED_HOSTS"
> git push -u origin master

If you remember we have Enabled the Automatic deployment. So, Heroku will start the deployment process automatically as soon as we push our code to the GitHub repository. (You can see the deployment logs in Activity tab of your Heroku dashboard)

Run the migrations and create tables in our PostgreSQL DB instance:

The way we do that is, we first log in to our heroku account through our command line tool.

So, go ahead and open windows CMD or power shell and run following command to login to your account:

> heroku login
'''It will ask'''
> heroku: Press any key to open up the browser to login or q to exit:

So, go ahead and hit enter. It will redirect you to the following page:

log.PNG Go ahead and hit login.

After logging in go to the CMD/powershell and run following commands:

> heroku run python3 manage.py makemigrations --app=your_app_name
> heroku run python3 manage.py migrate --app=your_app_name

To create superuser run following command:

> heroku run python3 manage.py createsuperuser --app=your_app_name

We've successfully deployed our Django + PostgreSQL web application on heroku!

If you face any problem during the deployment, Feel free to message me on my Instagram or LinkedIn or mail me your queries on .

Also, make sure to subscribe our newsletter on blog.learncodeonline.in and never miss any upcoming articles related to programming just like this one.

I hope this post will help you in your journey. Keep learning!

My GitHub and LinkedIn .

Did you find this article valuable?

Support Learn Code Online by becoming a sponsor. Any amount is appreciated!