Using `.env` file in a Django Project

A .env file is a file that resides at the root of a Django project. It is used to store environment variables. Environment variables are stored in key-value pairs.

Sensitive information such as passwords, secret keys, client IDs, or API keys is advised to be stored in this file.

To use a .env file in an application, you will need to install a package such as python-dotenv that can load the environment variables from the file into the application.

Here's how you can use it:

  1. Install python-dotenv:

     pip install python-dotenv
    
  2. Create a .env file at the root of your Django project and add all your environment variables.

     CLIENT_ID=DFHORE818374813204
     PASSWORD=whateveryourpasswordis.com
     DEBUG=True
    
  3. Add the following line of code to your Django settings file:

     import os
     from dotenv import load_dotenv
    
     # Load environment variables from .env file
     load_dotenv()
    
     # Access environment variables
     CLIENT_ID = os.getenv("CLIENT_ID")
     PASSWORD = os.getenv("PASSWORD")
    
     #To access a boolean variable, make it a conditional.
     DEBUG = os.getenv("DEBUG") == "True"
    

NOTE:

  1. DO NOT USE SINGLE OR DOUBLE QUOTES: You do not need to enclose the value in double quotes in a .env file. Double quotes are not required and will be treated as part of the string value.

    For example,

     # This is a valid line in a .env file
     PASSWORD=yourpassword
    
     # This is NOT a valid line in a .env file
     PASSWORD="yourpassword"
    

    The double quotes will be treated as part of the string value, so the actual value of the PASSWORD variable would be "yourpassword", including the quotes. This is probably not what you intended.

    In general, it's best to avoid using quotes around values in a .env file unless they are needed to specify a string value that contains spaces or other special characters.

  2. USE CAPITAL LETTERS FOR THE KEYS: This is just a common convention to use all capital letters for keys in a .env file to make them easier to distinguish from the values.

  3. Add the .env file to your .gitignore file to prevent it from being exposed.

  4. Spaces are not required between the keys and the values in a .env file

That's all...

Enjoy!