How to set up .env files in Django

agarjoshua

Agar Joshua

Posted on May 6, 2024

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:

  1. Download the Python Dotenv library:
pip install python-dotenv
Enter fullscreen mode Exit fullscreen mode
  1. Add or edit your '.env' file:
ENV_KEY = "your-key-goes-here"
Enter fullscreen mode Exit fullscreen mode
  1. 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))


Enter fullscreen mode Exit fullscreen mode

Note:

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

'.env' file file placement

💖 💪 🙅 🚩
agarjoshua
Agar Joshua

Posted on May 6, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related