Search code examples
pythondjangoubuntuvisual-studio-codepython-venv

How do you set Django environment variables with venv on linux?


I've tried using Python's os, manually typing the variables into the terminal, and using a .env file to set my environment variables but always get

raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.

Python

# env.py
import os
os.environ['SECRET_KEY'] = '<my secret key>'

Inside .env

export SECRET_KEY=<my secret key>

settings.py

SECRET_KEY = os.getenv("SECRET_KEY")

Running my python script will not make the environment variables persist.


  • Ubuntu 20.04.02
  • Django 3.1
  • Using VSCode

I have double checked the correct venv activated.

What am I doing wrong! Thanks


Solution

  • Django itself does not read .env file. The best way, to enable it is to use django-environ package

    Modify you settings.py

    import environ
    env = environ.Env(
        # set casting, default value
        DEBUG=(bool, False)
    )
    

    And .env file

    SECRET_KEY=your-secret-key