[Django]-How do I set the DJANGO_SETTINGS_MODULE env variable?

7👍

Do not set it from outside the application. Make a entry for DJANGO_SETTINGS_MODULE variable within your wsgi file. Everytime your server will be started, this variable will be set automatically.

For example:

import os
os.environ['DJANGO_SETTINGS_MODULE'] = '<project_name>.settings'

0👍

Are you on Mac or Linux? Then simply export DJANGO_SETTINGS_MODULE="project_name.settings.your_settings_file"
Make sure that if your settings file is in a folder, that there is also an __init__.py file in there.

On windows, I believe the equivalent is SET DJANGO_SETTINGS_MODULE="project_name.settings.your_settings_file, but I could be mistaken.

For django logging, see https://docs.djangoproject.com/en/1.10/topics/logging/

0👍

Just out of curiosity, I looked into the django code to find out where the settings for DJANGO_SETTINGS_MODULE in wsgi.py are executed.

$ python3
>>> from mysite import wsgi
Traceback (most recent call last):

from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
application = get_wsgi_application() =>

In "django/core/wsgi.py"
     def get_wsgi_application() => django.setup(set_prefix=False) =>
In "django/__init__.py"
      def setup(set_prefix=True):
              from django.conf import settings
              from django.utils.log import configure_logging
              configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
In "conf/__init__.py"
      settings = LazySettings()
class LazySettings(LazyObject):
    def __getattr__(self, name=LOGGING_CONFIG):
      self._setup(name)
    def _setup(self, name=None):
        settings_module = os.environ.get(ENVIRONMENT_VARIABLE)
        self._wrapped = Settings(settings_module)
class Settings:
    def __init__(self, settings_module):
        mod = importlib.import_module(settings_module)  

After which, we have settings.py imported and verified as below:
>>> mysite.settings.BASE_DIR            <<<===  verified
'/home/user/Documents/DjangoTutorial/mysite'
>>> mysite.settings.ROOT_URLCONF        <<<===  verified
'mysite.urls'

So it is first imported with configure_logging(settings.LOGGING_CONFIG)

Leave a comment