Search code examples
pythondjangodevelopment-environmentproduction-environment

Best way to handle different configuration/settings based on environment in Django project


Is DEBUG == False supposed to mean that the app is running in production environment?

At least, that's what I see occasionally on the internet. But what do I put in settings.py then? Okay, I can put local settings to, say, settings_local.py and import it from settings.py. But if some settings depend on environment, than I've got to put them after import statement. There more I think about it, the more I don't like it. And you?


Solution

  • As an answer to the question:

    Is DEBUG == False supposed to mean that the app is running in production environment?

    DEBUG is a configuration that you define in your setting.py file.

    • If set to True, in case of un-handled exception it displays the complete stack-trace along with the values of all the declared variables.

    • If set to False, your server just returns the 500 status code without any stack-trace.

    In production, you must have DEBUG set to False in order to prevent potential risk of security breach, and other information which you wouldn't want your user to know.


    In order to use different settings configuration on different environment, create different settings file. And in your deployment script, start the server using --settings=<my-settings.py> parameter, via which you can use different settings on different environment.

    Benefits of using this approach:

    1. Your settings will be modular based on each environment

    2. You may import the master_settings.py containing the base configuration in the environmnet_configuration.py and override the values that you want to change in that environment.

    3. If you have huge team, each developer may have their own local_settings.py which they can add to the code repository without any risk of modifying the server configuration. You can add these local settings to .gitnore if you use git or .hginore if you Mercurial for Code Version Control. That way local settings won't even be the part of actual code base keeping it clean.