[Answered ]-ImportError: Couldn't import Django inside virtual environment with poetry?

2πŸ‘

βœ…

It seems that you have manually created a virtual env in the project directory by e.g. python -m venv venv. So now you have one in /home/tesla/Documents/projects/graphql/graphenee/venv/.

After that you added some packages with poetry. However, 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 in /home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9 and installed the packages you added via poetry add there.

The problem is that you try to use the "empty" virtual env in the project directory instead of the one created by poetry. Fortunately with poetry it is very easy to run command, even without activating the venv, just use poetry run in the project directory.

To check Django installation:

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

To run Django management commands:

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

It will use the virtual env in /home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9. You can delete venv in the project directory.

Note: if you rather want to use a virtual env in the project directory, then delete /home/tesla/.cache/pypoetry/virtualenvs/graphenee-CXeG5cZ_-py3.9, then create one in the project directory by

python -m venv .venv`

After that install packages with poetry:

poetry install

Now poetry will use the local virtual env in /home/tesla/Documents/projects/graphql/graphenee/.venv when you run a command via poetry run [cmd].

πŸ‘€Dauros

0πŸ‘

I also had this issue when my project name was django. The name of the poetry virtual env was then also django, and when I ran poetry add django, nothing happened. When I renamed the project the issue was resolved.

πŸ‘€Tabs

-1πŸ‘

Simple solution:

ln -s venv .venv
poetry install

Leave a comment