You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django项目执行pytest时出现corsheaders模块找不到错误的解决咨询

问题排查与解决:pytest找不到已安装的corsheaders模块

核心原因

runserver能正常启动但pytest报错找不到模块,本质是pytest使用的Python环境与项目运行环境不一致——你的项目虚拟环境里已经安装了django-cors-headers,但pytest可能调用了全局Python或其他未安装该依赖的环境。

具体解决步骤

1. 强制使用项目环境运行pytest

直接用当前激活环境的Python调用pytest,避免环境混淆:

python -m pytest

(替代直接输入pytest命令,确保pytest使用的是和python manage.py runserver相同的Python解释器)

2. 验证环境一致性

分别执行以下命令,对比两个输出的Python路径是否一致:

  • 查看runserver使用的Python路径:
    python -c "import sys; print(sys.executable)"
    
  • 查看pytest使用的Python路径:
    pytest -c "import sys; print(sys.executable)"
    

如果路径不同,说明你需要激活项目对应的虚拟环境后再运行pytest。

3. 替换老旧的django-pytest包

你安装的django-pytest==0.2.0版本过于陈旧,早已停止维护,且与Django 4.0.7、Python 3.10兼容性极差,建议替换为官方维护的pytest-django:

# 卸载旧包
pip uninstall django-pytest -y
# 安装兼容的pytest-django
pip install pytest-django

替换后原pytest.ini配置无需修改,可正常使用。

4. 兜底:重新安装依赖

若上述步骤无效,尝试重新安装django-cors-headers确保依赖安装完整:

pip install --force-reinstall django-cors-headers==3.13.0

内容的提问来源于stack exchange,提问作者Cool Breeze

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 06:35:16