How to set up .env files in Django

How to set up .env files in Django

Many resources can be unclear when explaining how to set up environment variables in Django with ‘.env’ files. Here’s a straightforward guide:

Download the Python Dotenv library:

pip install python-dotenv

Add or edit your ‘.env’ file:

ENV_KEY = “your-key-goes-here”

Import it in your specific file(The file you want to include your ‘.env’ file values):

import os
from django.core.exceptions import ImproperConfigError
from django.views import View

#Import load_dotenv module
from dotenv import load_dotenv

class KeyValueView(View):
def get(self, request):
“””
Gets a key value from the .env file.

Raises:
ImproperConfigError: If the ENV_KEY environment variable is not set.
“””

# Load the dotenv function
load_dotenv()

try:
# Your key is imported here like so…
key = os.environ.get(ENV_KEY)
if not key:
raise ImproperConfigError(You must set the ENV_KEY environment variable.)
value = os.getenv(key)
return render(request, your_template.html, {key: key, value: value})
except ImproperConfigError as e:
return HttpResponseBadRequest(str(e))

Note:

Don’t commit or deploy your ‘.env’ file – (that goes without saying) you will compromise the security of your site if you do.
Your ‘.env’ file should be in your root directory. i.e

Leave a Reply

Your email address will not be published. Required fields are marked *