Heroku Postgres and deployment

Step 16: Use the following command to install four packages for database connection and deployment.

pip install psycopg2 gunicorn django-heroku whitenoise

Step 17: Log in to your Heroku app and follow the below instructions to add Postgres to your Django application.

  • Click “Create app”.
  • Name your app and click save, i.e. “gfg-tutorial”
  • Go to the “add-ons” section in elements or go to the new tab and search Heroku Add-ons.

 

  • Now, you will have clickable “Heroku Postgres” which opens in a new tab. Click to install.
  • Click on the Bento menu, and go to data or datastores.
  • Click “view credentials” under the settings tab to fetch your connection details.

 

Step 18: Open “settings.py” to make the following changes.

Python3




import django_heroku
  
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': '<DATABASE>',
        'USER': '<USER>',
        'PASSWORD': '<PASSWORD>',
        'HOST': '<HOST>',
        'PORT': '5432',
    }
}
  
# Optional section to include if 
# you want to include static files
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
django_heroku.settings(locals())


Also, modify “ALLOWED_HOSTS” as mentioned below to allow the Heroku app which we created now to host the application.

Python3




ALLOWED_HOSTS = ['gfg-tutorial.herokuapp.com']


Step 19: Additional files

  1. Create “runtime.txt” and “Procfile” in the project folder “geeks”.
  2. Run the following command to get all the packages listed in “requirements.txt”
pip freeze > requirements.txt

Step 20:  Open “runtime.txt” and add the following code.

python-3.10.7

Step 21:  Open “Procfile” and add the following code.

release: python manage.py migrate
web: gunicorn geeks.wsgi

Deploying Django App on Heroku with Postgres as Backend

Django is a high-level Python web framework used to create web applications without any hassle, whereas, PostgreSQL is a powerful, open-source object-relational database. Let us first create a Django application with PostgreSQL in the backend and deploy it in Heroku which is a container-based cloud Platform to deploy, manage, and scale the applications. 

Similar Reads

Packages Required

Python Django Postgres Virtual Environment Git...

File Structure

Project folder...

Set-up virtual environment :

In your terminal, use the following commands to set up a virtual environment for this tutorial. This will allow you to have a development environment independent of the host operating system....

Create Django application

Step 1. Django project set-up...

Heroku Postgres and deployment

...

Push to GitHub

...

Connect Postgres to a remote server(pgAdmin4)

...

Contact Us