contact@digitalnotebooks.co
Stay Organized, Stay Inspired. Let's Write.

Car Listing: Deployment using Heroku Part 19E - Environment Variables

Back To All Notes
  • Notebook: Django Project: Car Listing
  • Speaker:
  • Date Created: Aug. 3, 2024, 10:10 p.m.
  • Owner: Rosilie

Instead of explicitly adding the sensitive data like SECRET_KEY, DATABASE_URL, EMAIL AND PASSWORD, we can ENVIRONMENT VARIABLES in our .ENV file and setup our SETTINGS.PY to call this.

We can use CONFIG or GETENV FUNCTIONS.

In this project, we use GETENV.

1. Install DOT_ENV. Make sure to add this in your REQUIREMENTS.TXT

pip install python-dotenv
 

2. Create a .ENV file and set it up

SECRET_KEY=your-secret-key
DATABASE_URL=postgres://your-database-user:your-database-password@your-database-host:your-database-port/your-database-name

3.  Modify your SETTINGS.PY

import os
import dj_database_url
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.getenv('SECRET_KEY')

# Database
DATABASES = {
    'default': dj_database_url.config(default=os.getenv('DATABASE_URL'))
}

 

#Email configurations

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_PORT = 587

EMAIL_HOST_USER = os.getenv('EMAIL_HOST_USER')

EMAIL_HOST_PASSWORD = os.getenv('EMAIL_HOST_PASSWORD')

EMAIL_USE_TLS = True

4.  In your .GITIGNORE file, make sure .ENV is included so that when you pushed your files/folders to HEROKU SERVER, it's not added.

5. Now push all the changes to our Heroku server:

GIT STATUS

GIT ADD -A

GIT COMMIT -M "Your comment"

GIT PUSH HEROKU MAIN

6. To make sure that Heroku doesn't expose your sensitive data, we add this code in our  Heroku CLI terminal

heroku config:set SECRET_KEY='your-secret-key'
heroku config:set DATABASE_URL='postgres://your-database-user:your-database-password@your-database-host:your-database-port/your-database-name'

heroku config:set EMAIL_HOST_USER ='your-email_address'

heroku config:set EMAIL_HOST_PASSWORD ='your-email_password'

7.  Using HEROKU OPEN, you can load your app again and test for database functionality.

8. SInce our environment variables are all successfully setup, make sure that we update our GITHUB REPO. So we use HEROKU LOGOUT to logout from Heroku server. Then, in the terminal we issue our commands:

GIT STATUS

GIT ADD -A

GIT COMMIT -M "Your comment"

GIT PUSH ORIGIN MAIN

9. View your Github for the latest updates.

 



No PDF file attached.

Notebook
Notebook Details
Title: Django Project: Car Listing
Category: Udemy Django Course