简体   繁体   中英

Django cannot find new modules, using pyenv and virtualenv

I'm sure this is pretty straightforward to someone experienced. I'm learning Django through the Wedge of Django ebook.

I'm using Python 3.8.7 installed via pyenv like so: pyenv install 3.8.7

Then I've set up a virtualenv like so: pyenv virtualenv 3.8.7 everycheese

I activate the virtualenv in my repo like so: pyenv local everycheese

The environment is shown as active in the prompt, as it starts with (everycheese).

The main project is cloned from Django Cookiecutter https://github.com/cookiecutter/cookiecutter-django

I've then used pip to install requirements from the requirements.txt files.

However - I'm running into trouble when I try to add new packages (by adding the package to requirements.txt as a new line and installing again with pip).

pip list , or pip freeze both show the new module. But when I add the module to my INSTALLED_APPS and try to import it in my models.py file, Django cannot find it.

When I type which python , and which pip , they point to different directories and I think this may be part of the problem but I am stuck.

When using pip (or actually any other Python script), it is important to make sure which Python interpreter is used. Usually it is obvious which Python interpreter is used when calling pip . But sometimes it is not clear, and the script is actually running with a different interpreter that one might think. Which leads to unexpected results and a lot of confusion.

Therefore it is always better to call explicitly the exact Python interpreter you are targeting and tell it to run pip 's executable module (or any other executable module). Typically:

$ python -m pip install Something
$ # instead of 'pip install Something'
$ python3 -m pip install Something
$ # instead of 'pip3 install Something'

If there is still doubt, one could even go one step further and use a more explicit path to the Python interpreter explicitly:

  • /the/path/to/my/pythonX.Y -m pip
  • path/to/my/pythonX.Y -m pip
  • path/to/my/python -m pip
  • path/to/venv/bin/python -m pip
  • pythonX.Y -m pip
  • python3 -m pip
  • python -m pip

Resource :

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM