6

Working with VS Code 1.35.1 on ubuntu 16.04 with a Python 3.7.3 pipenv virtual environment, I am trying to set environment variables in a .env file, but for some reason the file doesn't seem to be recognized.

Can someone help me understand what I can do to give my (Django) app access to the environment variables, without needing to manually run pipenv shell.

Steps taken:
So, this is what I am doing exactly:

1 - I have set the Python interpreter for my project like so: ctrl + shift + p > Python: Select interpreter > Python 3.7.3 64-bit ('environment_name': pipenv)

2 - Created a .env file inside the project root directory:

# Django
SECRET_KEY="some key here"
DEBUG=True

...

3 - Made sure the VS Code Python extension is installed and enabled

4 - Adjusted my Django settings file to get the SECRET_KEY from the environment variables:

SECRET_KEY = os.getenv('SECRET_KEY')

5 - Running the Django development server from the VS Code terminal (with pipenv environment activated through ctrl + shift + ~):

(environment-name) user@system-name:~/projects/my-project$ python manage.py runserver

6 - No other settings changed

I haven't changed any settings, like the python.envFile setting. Settings are left to their defaults.

How I know that the .env file isn't recognized:

The above steps result in the following message in the VS Code terminal:

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

While if I run pipenv shell inside the same VS Code terminal (with the already activated environment, and thus activating it again), and start the Django dev server: python manage.py runserver, the server starts perfectly.

Rik Schoonbeek
  • 3,908
  • 2
  • 25
  • 43

2 Answers2

0

It looks like your interpreter is not picking up pipenv environment

1) check pipenv --where

2) see if in your settings.json file that your pythonPath variable is set to the location {pipenv --where}/bin/python{some version}

3) run again

0

Looks like this issue is still open in the vscode-python GitHub. Two solutions would be: a) to run .env separate from your pipenv activation; or b) follow the steps in here. Good luck!

jayg_code
  • 571
  • 8
  • 21