enrm
enrm

Reputation: 695

Django ImportError No module named x.settings

I have the following structure:

mysite
  -> manage.py
  -> mysite (again)
        -> __init__.py
        -> wsgi.py
        -> settings.py
         etc
  -> myapp
        -> __init__.py            
        -> myscript.py
        -> models.py
        etc

When I run a script from myapp (that does myapp-related things, putting stuff in a the database for example) i need to do

import django
django.setup()

in order to be able to from models import MyModel. But if i do this in the myapp directory, I get:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 53, in __getattr__
    self._setup(name)
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 41, in _setup
    self._wrapped = Settings(settings_module)
  File "C:\Python27\lib\site-packages\django\conf\__init__.py", line 97, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "C:\Python27\lib\importlib\__init__.py", line 37, in import_module
    __import__(name)
ImportError: No module named mysite.settings

Which I kind of understand since it's further up the directory tree and not in the same directory as e.g manage.py (the root I guess?). When I issue a python interpreter in mysite where manage.py is located, I dont get this error.

What should I do to be able to place my scripts in myapp and still be able to use django.setup() from that dir?

Upvotes: 0

Views: 942

Answers (1)

Mad Wombat
Mad Wombat

Reputation: 15105

You need to make sure the root of your project is in python path when you run the script. Something like this might help.

import os
import sys
projpath = os.path.dirname(__file__)
sys.path.append(os.path.join(projpath, '..'))

Upvotes: 1

Related Questions