努力让Django服务器在虚拟环境中运行

时间:2020-10-18 16:54:00

标签: python django

我是使用Django和Python的新手,在尝试使manage.py应用程序在虚拟环境中运行时遇到一些困难。

在我的models.py文件顶部出现以下错误:

最初,我认为这是pylint没有指向正确环境的问题(当我将Python解释器切换到虚拟环境之外的某个位置时,pylint错误消失了);但是,每当我尝试运行服务器时,都会出现以下错误:

(.venv) tjmcerlean@LAPTOP-RKLCBQLO:/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce$ python manage.py runserverTraceback (most recent call last):
  File "manage.py", line 10, in main
    from django.core.management import execute_from_command_line
  File "/mnt/c/Users/tjmce/Desktop/Git/CS50w/Project 2/commerce/.venv/lib/python3.8/site-packages/django/__init__.py", line 1, in <module>
    from django.utils.version import get_version
ModuleNotFoundError: No module named 'django.utils'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 12, in main
    raise ImportError(
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

此错误似乎表明未激活虚拟环境。但是,我使用虚拟环境的位置(.venv / bin / activate)激活了它,然后看到bash终端现在显示(.venv):

另外,当使用(pip Frozen)命令时,我可以看到Django也安装在虚拟环境中:

我不知道为什么服务器将无法运行,并且非常感谢任何建议。

谢谢!

2 个答案:

答案 0 :(得分:0)

在激活的环境中调用django.__file__会显示真实路径:

python -c "import django; print(django.__file__)"

它应该看起来像/usr/local/lib/python3.8/site-packages/django/__init__.py 然后重新检查PYTHONPATH环境变量。

也许您已经在venv和整个系统范围内安装了2个Django,但其中有些没有db。并删除您工作文件夹中的所有*.pyc文件。

答案 1 :(得分:0)

当您在virtualenv中不包含路径时,就会发生问题。

尝试在您的vscode上添加python的路径。 或者,尝试安装和卸载Django项目。