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.
Settings.py after modifications(Move default settings to new environment class)
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"
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:
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:
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)