Django Multiple environment in one file

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:

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.

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”

Comments