Set environments in django

Setting up environments in django is quite easy. You need to install “django-configurations” module to add multiple environments.

pip install django-configurations

# import configurations in settings.py file

from configurations import Configuration

# create default configuration class and move default settings to this class as shown below in the images.

Default settings.py

settings default

Settings.py after modifications(Move default settings to new environment class)

settings after modify

 

class Dev(Configuration):
    CURRENT_ENV_NAME = "Dev"

You can create more environment classes like Production, staging/UAT, local as per your requirement.

New environment class (Production) will override previous environment class (Dev)

class Production(Dev):
    CURRENT_ENV_NAME = "Production"

settings new env

You can add more environment classes as shown above in the image.

New environment class (Staging/UAT) will override previous environment class (Production)

class Staging(Production):
    CURRENT_ENV_NAME = "Staging"

New environment class (Local) will override previous environment class (Staging)

class Local(Staging):
    CURRENT_ENV_NAME = "Local"

set default configuration environment in manage.py file as shown below:

os.environ.setdefault('DJANGO_CONFIGURATION', 'Dev')

comment/remove following line in manage.py 

from django.core.management import execute_from_command_line

Add following line in manage.py so that django can use your configurations.

from configurations.management import execute_from_command_line

# Now your manage.py file will looks like:

manage after modification

enable/change/switch environment using configuration

python manage.py runserver --configuration=Production

If no configuration name is passed in the runserver command than default environment configuration which is defined in manage.py file will be called. 

python manage.py runserver

This will call default environment “Dev”

To check current environment, you can access CURRENT_ENV_NAME variable defined in environment classes.

For example, in your views.py file, you can print current environment.

from django.conf import settings

print("Current environment is: ", settings.CURRENT_ENV_NAME)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top
Shares