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

pytest无法找到Django配置目录及settings文件问题求助

解决pytest无法找到Django settings配置文件的问题

环境与报错

环境:virtualenv、Python 3.11.9、pytest 8.3.2
启动pytest时出现以下错误:

ImportError: No module named 'drf.settings'
pytest-django could not find a Django project (no manage.py file could be found). You must explicitly add your Django project to the Python path to have it picked up.

项目结构

├── README.md
├── drf
│   ├── drf
│   │   ├── __init__.py
│   │   ├── production_settings.py
│   │   ├── settings.py
│   │   ├── urls.py
│   │   └── wsgi.py
│   ├── manage.py
│   └── tests
│       ├── __pycache__
│       │   └── test_auth.cpython-311-pytest-8.3.2.pyc
│       ├── factory_boy
│       │   ├── __pycache__
│       │   │   └── factory_models.cpython-311.pyc
│       │   └── factory_models.py
│       └── test_auth.py
├── drf-uwsgi.ini
├── pytest.ini
├── requirements.in
├── requirements.txt

当前pytest.ini配置

[pytest]
DJANGO_SETTINGS_MODULE = drf.settings
python_files = test_*.py
django_debug_mode = true
pythonpath = .venv/bin/python

已尝试的无效操作

  • 为tests目录添加__init__.py(不推荐且无效)
  • 重新激活virtualenv
  • 将DJANGO_SETTINGS_MODULE改为drf.drf.settings,无效果
  • 以模块方式执行python -m pytest tests

补充:目前通过conftest.py可正常运行pytest,但希望通过配置pytest.ini解决问题。

解决方案

核心问题

pytest.ini中的pythonpath配置错误,它指向了Python解释器的路径,而非Django项目的根目录,导致pytest无法定位到settings模块和manage.py文件。

修正后的配置方案

提供两种可行的配置:

方案一:指定项目根目录到pythonpath

[pytest]
DJANGO_SETTINGS_MODULE = drf.settings
python_files = test_*.py
django_debug_mode = true
pythonpath = ./drf

将pythonpath设置为包含manage.py的外层drf目录,pytest会把该目录加入模块搜索路径,从而找到内层drf包中的settings.py。

方案二:使用完整settings模块路径

[pytest]
DJANGO_SETTINGS_MODULE = drf.drf.settings
python_files = test_*.py
django_debug_mode = true
pythonpath = .

保持pythonpath为当前目录(pytest.ini所在目录),通过完整的模块路径drf.drf.settings指定配置文件,Python会从当前目录开始定位到内层drf包中的settings文件。

验证

保存修改后的pytest.ini,在项目最外层目录直接执行pytest命令即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 02:22:44