Can't import anything that depends on DANGO_SETTINGS_MODULE in project's `__init__.py` file.
|Reported by:||mrmachine||Owned by:||nobody|
|Severity:||Keywords:||DJANGO_SETTINGS_MODULE settings import|
|Has patch:||yes||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I've got some basic code to register signal handlers in my project's __init__.py, as this seems the only place certain (or as close to certain as possible) to execute whenever Django is started with the runfcgi, runserver, shell, etc. management commands.
For example, if I import settings from django.conf, or any other module that relies on settings:
from django.conf import settings if settings.DEBUG: ...
from django.db import models
The following exception is raised:
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
The reason is because django.core.management.setup_environ adds DJANGO_SETTINGS_MODULE to os.environ *after* importing the project module.
As far as I can tell, the fix is easy. Just move the assignment to os.environ up a few lines, before the import. I can't see how this could possibly break any existing code, nor any reason *not* to do it. We're not adding any code or functionality, just executing it earlier.