Let's first install the package that is going to take care of loading our virtual environment:
pip install python-dotenv
Then, in your settings.py:
import os
from dotenv import load_dotenv
load_dotenv()
The DEBUG variable:
DEBUG = os.getenv('DEBUG', 'True') == 'True'
Change the DEBUG environment variable from DEBUG=True to the code above.
The code above will try to load an environment variable called DEBUG.
The comparison os.getenv('DEBUG') == 'True'
compares the retrieved value with the string 'True'
. This comparison will be True
if the value of the DEBUG
environment variable is 'True'
, and False
otherwise.
The SECRET_KEY:
SECRET_KEY = os.getenv('SECRET_KEY', 'your-secret-key')
Note: Replace 'your-secret-key' with the secret key that previously existed in your django project.
The ALLOWED_HOSTS:
ALLOWED_HOSTS = os.getenv('ALLOWED_HOSTS', '127.0.0.1').split(',')
For the ALLOWED_HOSTS, if the environment variable is not set or is empty, the default value ''
will be used. The split(',')
method splits the value by commas and returns a list of host names.