简体   繁体   English

Django ImportError没有名为x.settings的模块

[英]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 当我从myapp运行脚本(执行与myapp相关的事情,例如将内容放入数据库中)时,我需要做

import django
django.setup()

in order to be able to from models import MyModel . 为了能够from models import MyModel But if i do this in the myapp directory, I get: 但是,如果我在myapp目录中执行此操作,则会得到:

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 eg manage.py (the root I guess?). 我理解这一点,因为它位于目录树的更manage.py而不是与例如manage.py (我猜是根)相同的目录中。 When I issue a python interpreter in mysite where manage.py is located, I dont get this error. 当我在manage.py所在的mysite中发出python解释器时,我没有收到此错误。

What should I do to be able to place my scripts in myapp and still be able to use django.setup() from that dir? 我应该怎么做才能将脚本放入myapp并仍然可以从该目录使用django.setup()

You need to make sure the root of your project is in python path when you run the script. 运行脚本时,需要确保项目的根目录位于python路径中。 Something like this might help. 这样的事情可能会有所帮助。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM