How to ensure changes to variables in .env file reflect in Django project?

I'm encountering an issue in my Django project where changes made to variables in the .env file do not seem to be reflected when I restart the server.

Here are the steps I've taken:

  • Verified that the .env file is in the correct location and its name is exactly .env.
  • Restarted the Django development server after making changes to the .env file.
  • Double-checked the syntax of the .env file for any errors or typos.
  • Cleared the cache after making changes to the .env fil (using python manage.py clear_cache)

Are you using some packages to support .env files; like django-environ? If not please install a package and add a code like this after setting BASE_DIR form the settings.py file:

# Take environment variables from .env file
environ.Env.read_env(os.path.join(BASE_DIR, '.env'))

And after that, you can check the values loaded successfully like print(os.environ.get("DB_NAME")) and finally you can use the environment variables for your settings:

DATABASES = {
    "default": {
        "ENGINE": 'django.db.backends.mysql',
        "NAME": os.environ.get("DB_NAME", "db_name"),
        "USER": os.environ.get("DB_USER", "db_user"),
        "PASSWORD": os.environ.get("DB_PASSWORD", "db_password"),
        "HOST": os.environ.get("DB_HOST", "localhost"),
        "PORT": os.environ.get("DB_PORT", "3306"),
    }
}

The second parameter from the os.environ.get() is the fallback values.

Back to Top