当我将 rest_framework 添加到我的 Django 应用程序时,为什么会出现 ModuleNotFoundError

Why am i getting a ModuleNotFoundError when i add rest_framework to my django app

我创建了一个新的 django 应用程序并使用 pipenv 版本 2020.11.15 安装了 djangorestframework 并将其注册到 settings.py 文件

# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'leads',
    'rest_framework'
]

我在 运行 python manage.py makemigrations

上遇到了这个错误
C:\Users\eliHeist\Python Workspace\lead_manager_react_django\leadmanager>python manage.py makemigrations
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 419, in
execute_from_command_line
    utility.execute()
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in
execute
    django.setup()
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\site-packages\django\apps\config.py", line 224, in create
    import_module(entry)
  File "C:\Users\eliHeist\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'rest_framework'

这是怎么回事?

使用

检查虚拟环境中安装的包
$ pip freeze

如果您在列表中找不到 "djangorestframework" 包,那么它没有安装,通过 $ pip install djangorestframework

安装 django rest framework

看起来您正在为虚拟环境使用 pipenv

使用

激活项目文件夹中的虚拟环境
$ pipenv shell

并安装所需的包,即 django、djangorestframework 等。喜欢

$ pipenv install djangorestframework

如果您使用的是 pipenv,请使用 $ pipenv install {package-name}