首页 文章

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

提问于
浏览 1744
1

我正在尝试选择一个旧的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

    每个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
    
  • 0

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

    myproject
        myproject
            __init__.py
            settings.py
        app1
        app2
    

    您可以通过示例和变体来了解这一点 .

    请注意,在顶级 myproject 下面有一个包含设置的 myproject 目录 .

    你看这些都是这样吗?

    或者您最初的目标是使用不同布局的旧版Django?

    如果您尝试这样做:

    PYTHONPATH=/Users/jonathan python
    import pragmatometer
    

    就像在你的第二个代码块中一样,它会将 /Users/jonathan 视为Python包并查找 /Users/jonathan/__init__.py ,这可能不会检查 /Users/jonathan/pragmatometer/settings.py .

  • 0

    我找到了罪魁祸首,或者至少是罪魁祸首 . 我省略了(在我的.bashrc中)“导出”,现在我又遇到了另一个问题 .

相关问题