I have a Django project which seemed to work pretty well with settings.py, which also imported a local_settings.py without problem.
I've now added the following lines at the end of the settings file :
try:
from extras import *
except ImportError, e:
print "import extras failed :: " + `e`
extras.py is a file of extra configuration information sitting in the same directory as settings.py and local_settings.py, however, I'm now getting :
import extras failed :: ImportError('Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.',)
This seems to be due to me trying to
from django.contrib.auth.models import User,UserManager
from django.db import models
in that extras.py file.
Anyone have any ideas?
cheers
Typically, having a line like
from django.db import models
in settings.py
will lead to a circular dependency. This causes an import error, which gets reported slightly differently in different versions of Django. For example, if I add that line to a working Django setup and invoke "manage.py shell", I get:
Error: Can't find the file 'settings.py' in the directory containing './manage.py'. It appears you've customized things. You'll have to run django-admin.py, passing it your settings module. (If the file settings.py does indeed exist, it's causing an ImportError somehow.)
If I remove that line, everything's fine again.
The reason is that Django's model loading machinery (located in the django.db.models
package) imports settings.py
, reads its INSTALLED_APPS
to see what apps should be installed, and then loads those apps. (You can confirm this by adding a print statement to __init__.py
for one of your installed apps.)
If you try to import django.db
stuff in settings.py
, that will lead to a circular import dependency and an ImportError
-related error message.
One workaround is to move the functionality which requires the problematic imports (and the imports themselves) to an app.
So how is DJANGO_SETTINGS_MODULE
set in your environment? It could be either that, or the result of the implicit import of settings which your other nested imports are causing while settings is being imported, a "circular dependency" that can have several nasty effects (though I don't believe it would have the specific one you're observing, so I lean towards the first hypothesis).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With