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

Django项目中pytest配置失败运行报错,请求排查原因

Django + Pytest 配置错误修复

项目结构

backend
  |-foodgram
        |-foodgram
        |-manage.py
  |-api
  |-users
  |-tests
  |-pytest.ini

错误信息

ERROR backend/tests/test_user.py - django.core.exceptions.ImproperlyConfigured: Requested setting REST_FRAMEWORK, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

当前pytest.ini配置

[pytest]
python_paths = foodgram/
DJANGO_SETTINGS_MODULE = foodgram.settings
norecursedirs = env/*
addopts = -vv -p no:cacheprovider
testpaths = tests/
python_files = test_*.py

修复方案

  • 调整python_paths路径:你的foodgram.settings模块实际位于backend/foodgram/foodgram/目录下,原配置的python_paths = foodgram/仅指向外层foodgram目录,导致pytest无法找到内层的settings模块。修改后的配置如下:
[pytest]
python_paths = foodgram/foodgram/
DJANGO_SETTINGS_MODULE = foodgram.settings
norecursedirs = env/*
addopts = -vv -p no:cacheprovider
testpaths = tests/
python_files = test_*.py
  • 快速验证方式:若不想修改配置文件,可在运行pytest时手动指定环境变量测试:
DJANGO_SETTINGS_MODULE=foodgram.settings pytest

如果此命令能正常执行,即可确认问题源于路径配置错误。

  • 运行路径检查:确保在backend目录下执行pytest命令,因为pytest.ini存放于此,pytest会优先读取当前工作目录下的配置文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 06:01:00