Home/Django Multiple environment in one file

Django Multiple environment in one file

Published On: 22 February 2020.By .
  • General

There are some points where we have to maintain settings for multiple environments. Django provides a very useful solution, to maintain multiple settings in a single file.

For that you need to install “django-configurations”.

pip install django-configurations

After installing “django-configurations” we have to import Configuration class in settings.py file, and the file should look like this:

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
from configurations import Configuration

class Dev(Configuration):
    DEBUG = False


    # Application definition

    CLOVER_URL = "url_for_dev"
    CMA_URL = "url_for_dev"
    SYNC_URL = "url_for_dev"

Defining Settings:

Now we have to defines settings in settings.py file under the classes.

First class must inherit and overwrite the Configuration class, which is already shown in the given example

As mentioned in the example, there is a Dev class which is inheriting the Configuration class and overwriting the properties of that.

We can use Dev class as a common class or can define all settings in the class. For defining other settings we have to create another class, and if we want some common settings then we have to inherit the Dev class and overwrite the settings which we requires.

class Production(Dev):
    # UAT
    CLOVER_URL = "url_for_production"
    CMA_URL = "url_for_production"
    SYNC_URL = "url_for_production"

class ProductionNew(Production):
    CLOVER_URL = "url_for_production_new"
    CMA_URL = "url_for_production_new"
    SYNC_URL = "url_for_production_new"

As shown in example, there are two classes Production and ProductionNew which are inheriting Dev and Production class respectively. Production class is overwriting Dev class and ProductionNew class is overwriting Production class.

After that we have to change the configurations in manage.py file. Where we replace the management command with the given below command:

from configurations.management import execute_from_command_line

After successfully completing this we have to run the server as the below mentioned command:

Python manage.py runserver --configuration=<?environment class name?>

default environment configuration from manage.py file will be called if no configuration name is passed in the runserver command.

python manage.py runserver

This will call default environment “Dev”

Related content

We Love Conversations

Say Hello
Go to Top