2012-07-28 79 views
1

我在默认位置的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的,我根本没有太多尚未进口。出于显而易见的原因,我需要能够将我的模型导入到我可以进行单元测试的其他模块,或者我需要另一个简单的工作流程来完成相同的工作。

+0

要在命令行使用模型,你应该**总是**使用'./manage.py shell'启动shell,而不是直接进入Python。这将避免与DJANGO_SETTINGS_MODULE相关的问题。 – 2012-07-28 22:31:10

+0

是产生... >>>进口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

回答

2

如果PythonFinal/home/users/jeremy/django/PythonFinal,然后/home/users/jeremy/django应该在你的PYTHONPATH环境变量,DJANGO_SETTINGS_MODULE应设置为"PythonFinal.PythonFinal.settings"。然后你可以使用

from PythonFinal.fertility.models import Cycle, Period 

从Python命令行。

它,然而,更常见的有settings.py文件相同的文件夹为manage.py,以及一些工具和教程预计这种设置...

+0

我将这些值添加到〜/ .bashrc并找到它,现在我只是得到ImportError:No module named MySiteDir.fertility.models – jeremyjjbrown 2012-07-28 23:10:47

+0

你能用真实的目录结构更新你的问题吗? – thebjorn 2012-07-29 13:23:55

+0

目录更新:) – jeremyjjbrown 2012-07-29 14:19:39