ImportError: Couldn't import Django inside virtual environment with poetry?

ImportError: Couldn't import Django inside virtual environment with poetry?

我创建了一个django项目,设置了一个虚拟环境,并用poetry add添加了django。

里面 pyproject.toml:

[tool.poetry.dependencies]
python = "^3.9"
psycopg2-binary = "^2.9.3"
Django = "^4.0.1"

我在 venv 里面 运行 poetry show:

asgiref         3.5.0 ASGI specs, helper code, and adapters
django          4.0.1 A high-level Python web framework that encourages rapid development and clean, pragmatic design.
psycopg2-binary 2.9.3 psycopg2 - Python-PostgreSQL Database Adapter
sqlparse        0.4.2 A non-validating SQL parser.

当我运行命令创建应用程序时:

  p manage.py startapp users apps/users

我收到这个错误:

    (base) ┌──(venv)─(tesla㉿kali)-[~/Documents/projects/graphql/graphenee]
└─$ p                                                                                                                                                                                                                                    1 ⨯
Python 3.9.7 (default, Sep 16 2021, 13:09:58) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'django'
>>> 

venv 已设置、激活,django 已安装,但我仍然收到此错误。在虚拟环境中,我开始 python shell 并导入 django:

    Python 3.9.7 (default, Sep 16 2021, 13:09:58) 
    [GCC 7.5.0] :: Anaconda, Inc. on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import django
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ModuleNotFoundError: No module named 'django'

Django 也是全局安装的,当我在全局环境中启动 python shell 时,我可以导入 django:

Python 3.9.7 (default, Sep 16 2021, 13:09:58) 
[GCC 7.5.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import django
>>> 

看来您在项目目录中手动创建了一个虚拟环境,例如python -m venv venv。所以现在你在 /home/tesla/Documents/projects/graphql/graphenee/venv/.

中有一个

之后你添加了一些带有诗歌的包。但是,by default poetry will only look for .venv directory (note the starting dot) in the project directory. Since poetry did not find a .venv, it created a new virtual env/home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9 中并安装了您通过 poetry add 添加的软件包。

问题是您尝试使用项目目录中的“空”虚拟环境,而不是 poetry 创建的虚拟环境。幸运的是,使用 poetry 很容易 运行 命令,即使不激活 venv,只需在项目目录中使用 poetry run

检查 Django 安装:

poetry run python
# Executes: /home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9/bin/python
>>> import django

至运行 Django管理命令:

poetry run ./manage.py startapp users apps/users

它将使用/home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9中的虚拟环境。可以删除项目目录下的venv

注意:如果您想在项目目录中使用虚拟环境,请删除/home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9,然后通过

在项目目录中创建一个
python -m venv .venv`

然后用诗歌安装包:

poetry install

现在,当您通过 poetry run [cmd] 命令 运行 时,诗歌将使用 /home/tesla/Documents/projects/graphql/graphenee/.venv 中的本地虚拟环境。