[Fixed]-Where do I set environment variables for Django?

11👍

create a file called .bashrc in your server

export('the_name_in_bashrc', some_value)

then in the settings.py

import os
some_variable = os.environ.get('the_name_in_bashrc')

19👍

.bashrc will work for local development but not for a production environment. I just spent quite a bit of time looking for the answer to this and here’s what worked for me:

1) Create a file somewhere on your server titled settings.ini. I did this in /etc/project/settings.ini

2) Add your config data to that file using the following format where the key could be an environmental variable and the value is a string. Note that you don’t need to surround the value in quotes.

[section]
secret_key_a=somestringa
secret_key_b=somestringb

3) Access these variables using python’s configparser library. The code below could be in your django project’s settings file.

from configparser import RawConfigParser

config = RawConfigParser()
config.read('/etc/project/settings.ini')

DJANGO_SECRET = config.get('section', 'secret_key_a')

Source: https://code.djangoproject.com/wiki/SplitSettings (ini-style section)

14👍

The simplest solution is as already mentioned using os.environ.get and then set your server environment variables in some way (config stores, bash files, etc.)

Another slightly more sophisticated way is to use python-decouple and .env files. Here’s a quick how-to:

1) Install python-decouple (preferably in a venv if not using Docker):

pip install python-decouple

2) Create a .env file in the root of your Django-project, add a key like;

SECRET_KEY=SomeSecretKeyHere

3) In your settings.py, or any other file where you want to use the configuration values:

from decouple import config

...

SECRET_KEY = config('SECRET_KEY')

4) As you probably don’t want these secrets to end up in your version control system, add the file to your .gitignore. To make it easier to setup a new project, you could have a .env_default checked into the VCS containing default/dummy-values that’s not used in production.

8👍

If you’re using a virtual ENV you can add the environment variables to that specific environment. You can use export KEY=VALUE in your terminal but that will not persist. If you would like your values to persist you can edit the file:

sudo nano your_environment/bin/activate

Then at the bottom add the values you want e.g.:

export MY_KEY="12345"

And save. Remember to restart your ENV for changes to take effect.

👤Josh

1👍

pip install python-dotenv

Go To settings.py

import os
from dotenv import load_dotenv

load_dotenv('.env')

SECRET_KEY = os.getenv('SECRET_KEY')

Go To .env file

SECRET_KEY =  your_secret_key 

Leave a comment