我在默认位置的models.py模块中有两个模型类。将django模型类导入实用程序模块
PythonFinal
|_ manage.py
|_ template
|_ PythonFinal
| |_ __init__.py
| |_ settings.py
| |_ urls.py
| |_ swgi.py
|
|
|___ fertility
|_ __init__.py
|_ models.py
|_ tests.py
|_ views.py
|_ dateUtils.py
我只想类导入dateUtils.py
from fertility.models import Cycle, Period
if __name__ == '__main__':
p1 = Period(periodFirstDay='2012-7-26' , periodNumber=4)
如果我运行这个模块,我得到
ImportError: no module named fertility
如果我试图从Python命令行导入模型我得到
import models
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "models.py", line 1, in <module>
from django.db import models
File "/usr/local/lib/python2.6/dist-packages/django/db/__init__.py", line 11, in <module>
if DEFAULT_DB_ALIAS not in settings.DATABASES:
File "/usr/local/lib/python2.6/dist-packages/django/utils/functional.py", line 184, in inner
self._setup()
File "/usr/local/lib/python2.6/dist-packages/django/conf/__init__.py", line 40, in _setup
raise ImportError("Settings cannot be imported, because environment variable %s is undefined." % ENVIRONMENT_VARIABLE)
ImportError: Settings cannot be imported, because environment variable DJANGO_SETTINGS_MODULE is undefined.
I将我的项目根文件夹添加到〜/ .bashrc中的PYTHONPATH中。 我wsgi.py读取
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "PythonFinal.settings")
我不认为这是不是一个圆形的进口,因为我得到的导入错误,而不是一个NamingError的,我根本没有太多尚未进口。出于显而易见的原因,我需要能够将我的模型导入到我可以进行单元测试的其他模块,或者我需要另一个简单的工作流程来完成相同的工作。
要在命令行使用模型,你应该**总是**使用'./manage.py shell'启动shell,而不是直接进入Python。这将避免与DJANGO_SETTINGS_MODULE相关的问题。 – 2012-07-28 22:31:10
是产生... >>>进口fertility.dateUtils.py 回溯(最近通话最后一个): 文件 “”,1号线,在 文件“/home/jeremy/PythonFinal/fertility/dateUtils.py “,第12行,在 from PythonFinal.fertility.models import Cycle,Period ImportError:没有一个名为fertility.models的模块 –
jeremyjjbrown
2012-07-28 23:04:33