为什么我不能在Django项目中导入模块?

时间:2015-09-02 19:41:41

标签: python django import django-dev-server

我正在尝试选择一个旧的Django项目,我的目标是看看我可以在开发服务器上的计算机上运行什么。我明白了:

Inner Sanctum ~/pragmatometer $ python manage.py runserver
Traceback (most recent call last):
  File "manage.py", line 10, in 
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 399, in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 392, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 261, in fetch_command
    commands = get_commands()
  File "/Library/Python/2.7/site-packages/django/core/management/__init__.py", line 107, in get_commands
    apps = settings.INSTALLED_APPS
  File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 54, in __getattr__
    self._setup(name)
  File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 49, in _setup
    self._wrapped = Settings(settings_module)
  File "/Library/Python/2.7/site-packages/django/conf/__init__.py", line 132, in __init__
    % (self.SETTINGS_MODULE, e)
ImportError: Could not import settings 'pragmatometer.settings' (Is it on sys.path? Is there an import error in the settings file?): No module named pragmatometer.settings

这是一些命令行输出:

Inner Sanctum ~/pragmatometer $ /bin/pwd
/Users/jonathan/pragmatometer
Inner Sanctum ~/pragmatometer $ echo $PYTHONPATH
/Users/jonathan
Inner Sanctum ~/pragmatometer $ python
Python 2.7.10 (default, Jul 14 2015, 19:46:27) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pragmatometer
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named pragmatometer
>>> import pragmatometer.settings
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named pragmatometer.settings
>>> 

我应该做什么,我不是? (或者,因为这是一个较旧的项目,我应该从一个全新的项目开始吗?)

谢谢,

3 个答案:

答案 0 :(得分:0)

每个django项目都附带一个settings.py文件,django将拒绝运行或加载模型,直到加载了settings.py文件。

settings.py文件需要位于模块中,并且是当前PYTHONPATH的一部分,并且 ENV。应将变量DJANGO_SETTINGS_MODULE设置为它。

例如:

# assuming your file is under /myproject/mywebsite/settings.py
export PYTHONPATH=/myproject/
export DJANGO_SETTINGS_MODULE=mywebsite.settings

答案 1 :(得分:0)

Django项目通常看起来像这样(我认为是Django 1.4及以上版本)。

myproject

您可以look around online了解相关示例和变体。

请注意,顶级myproject下有PYTHONPATH=/Users/jonathan python import pragmatometer 目录,其中包含设置。

你看这些都是这样吗?

或者你最初的目标是使用不同版面的旧版Django吗?

如果您尝试这样做:

/Users/jonathan

就像你的第二个代码块一样,它会将/Users/jonathan/__init__.py视为Python包,并寻找可能不存在的/Users/jonathan/pragmatometer/settings.py,所以它赢了&# 39; t检查{{1}}。

答案 2 :(得分:0)

我找到了罪魁祸首,或者至少是罪魁祸首。我已经省略了(在我的.bashrc中)" export",现在我已经解决了另一个问题。