nothingness
nothingness

Reputation: 1031

How do you add environment variables to your django project

I'm trying to set up my project so that it can use environment variables locally

Ive tried adding it to the end of my activate file and a list of other things. I'm trying to use this

from .base import *

    if os.environ['DJANGO_SERVER_TYPE'] == 'local':
        try:
            from .local import *
        except:
            pass

    if os.environ['DJANGO_SERVER_TYPE'] == 'production':
        try:
            from .production import *
        except:
            pass

I am a real novice and often things are explained brief and matter of factly. So a thorough explanation would really be beneficial to me in how to implement this thanks. I've NEVER done anything n Bash. Ive tried doing this

export KEY=VALUE

in the activate file, only for it not to be recognized by the system, and I had to remove it in order to use my local server

Upvotes: 9

Views: 27592

Answers (3)

kojiro
kojiro

Reputation: 77187

I have a settings module that contains something like the following:

…
import os
from django.core.exceptions import ImproperlyConfigured
…

def _require_env(name):
    """Raise an error if the environment variable isn't defined"""
    value = os.getenv(name)
    if value is None:
        raise ImproperlyConfigured('Required environment variable "{}" is not set.'.format(name))
    return value

…

SECRET_KEY = _require_env('SOMETHING_SECRET_KEY')

_db_host = os.getenv('SOMETHING_MYSQL_HOST', 'mysql')
_db_port = os.getenv('SOMETHING_MYSQL_PORT', 3306)   
_db_name = _require_env('SOMETHING_MYSQL_DATABASE')         
_db_user = _require_env('SOMETHING_MYSQL_USER')             
_db_password = _require_env('SOMETHING_MYSQL_PASSWORD')

DATABASES = {'default': {'ENGINE': 'django.db.backends.mysql',
                     'NAME': _db_name,                    
                     'HOST': _db_host,                    
                     'PORT': _db_port,                    
                     'USER': _db_user,                    
                     'PASSWORD': _db_password,
    … } }

and so on.

_require_env is for environment variables that must be set. If those environment values are not found, Django immediately raises an ImproperlyConfigured error. In other cases I just use os.getenv with a default value.

Upvotes: 3

tennismogul
tennismogul

Reputation: 445

If you're running it through the Django web server, you can pass environment variables the same way you would to any other command:

DJANGO_SERVER_TYPE="local" ./manage.py runserver

If you're running it through a web server like Apache, you can set environment variables through your virtual host configuration:

SetEnv DJANGO_SERVER_TYPE local

Upvotes: 13

jauyeung
jauyeung

Reputation: 11

Install the environ library and add the following code to your settings file:

root_path = environ.Path(__file__) - 2
env = environ.Env(DEBUG=(bool, False), DJANGO_ENV=(str, 'dev')) # set default    values and casting
environ.Env.read_env(root_path('.env')) 

Add a file called .env on the root of your project folder with variables formatted like:

DEBUG=on    

Upvotes: 1

Related Questions