解决python manage.py shell ModuleNotFoundError: No module named xxx

报错如下:

python 复制代码
python manage.py shell

Traceback (most recent call last):
  File "/Users/z/Documents/project/c/manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/Users/z/.virtualenvs/c/lib/python3.12/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line
    utility.execute()
  File "/Users/z/.virtualenvs/c/lib/python3.12/site-packages/django/core/management/__init__.py", line 416, in execute
    django.setup()
  File "/Users/z/.virtualenvs/c/lib/python3.12/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/z/.virtualenvs/c/lib/python3.12/site-packages/django/apps/registry.py", line 91, in populate
    app_config = AppConfig.create(entry)
                 ^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/z/.virtualenvs/c/lib/python3.12/site-packages/django/apps/config.py", line 193, in create
    import_module(entry)
  File "/opt/homebrew/Cellar/python@3.12/3.12.3/Frameworks/Python.framework/Versions/3.12/lib/python3.12/importlib/__init__.py", line 90, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap>", line 1387, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1360, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1324, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'xxx'

原因 是 manage.py文件里的内容没有导入项目的路径到环境变量里,正确的内容如下:

python 复制代码
import os
import sys

if __name__ == "__main__":
    app_path = os.path.dirname(sys.path[0])
    sys.path.append(app_path)
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "xxx.settings")
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
相关推荐
多恩Stone1 小时前
【3DV 进阶-2】Hunyuan3D2.1 训练代码详细理解下-数据读取流程
人工智能·python·算法·3d·aigc
xiaopengbc1 小时前
在 Python 中实现观察者模式的具体步骤是什么?
开发语言·python·观察者模式
Python大数据分析@1 小时前
python用selenium怎么规避检测?
开发语言·python·selenium·网络爬虫
ThreeAu.2 小时前
Miniconda3搭建Selenium的python虚拟环境全攻略
开发语言·python·selenium·minicoda·python环境配置
偷心伊普西隆2 小时前
Python EXCEL 理论探究:格式转换时处理缺失值方法
python·excel
精灵vector3 小时前
LLMCompiler:基于LangGraph的并行化Agent架构高效实现
人工智能·python·langchain
java1234_小锋3 小时前
Scikit-learn Python机器学习 - 特征降维 压缩数据 - 特征选择 - 移除低方差特征(VarianceThreshold)
python·机器学习·scikit-learn
万邦科技Lafite3 小时前
实战演练:通过API获取商品详情并展示
大数据·数据库·python·开放api接口