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

Django教程第5章:Python Shell访问response.context报TypeError错误

Django测试客户端response.context为None的解决办法

问题重现

按照Django官方教程操作测试客户端时,执行response.context['latest_question_list']触发TypeError: 'NoneType' object is not subscriptable,但视图已正常返回200状态码且页面内容正确。

解决步骤

  1. 打开项目根目录的settings.py文件,确认DEBUG参数设置为True:
DEBUG = True
  1. 重新启动python manage.py shell,再次执行测试客户端的代码,此时response.context['latest_question_list']即可正常返回预期的QuerySet。

原因说明

当Django处于DEBUG=False的生产模式时,会隐藏模板上下文信息以保证安全性和性能,因此response.context会返回None。开发环境下开启DEBUG=True后,调试模式会保留上下文数据,允许你通过response.context访问视图传递给模板的变量。

如果是编写自动化测试用例,继承自django.test.TestCase的测试类会自动配置环境,无需额外修改DEBUG参数即可正常访问response.context。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 23:05:33