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

Django模板引擎调用Python对象超出最大递归深度报错如何解决

错误原因

你的模板代码形成了无终止的递归引用闭环,直接触发递归深度超限错误:

  • Homepage/index.html第一行执行{% include "article/sale.html" %},渲染index模板时会优先加载sale.html的内容
  • sale.html第一行执行{% extends "Homepage/index.html" %},渲染sale模板时会优先加载父模板index.html的内容
    两者循环互相调用,没有终止条件,最终超过Python默认的递归深度限制抛出报错。
    另外注意你的路径存在笔误:views中sale视图加载的是articles/sale.html,而index里include写的是article/sale.html,路径不一致也会额外触发模板不存在错误,需要同步修正。
解决方法

根据你的使用场景选择对应方案即可:

方案1:需要同时支持index页面展示sale区块、sale路由独立渲染sale页面

抽离公共内容避免循环引用:

  1. 新建独立片段模板articles/sale_fragment.html,内容为原sale.html中block包裹的业务代码,不需要加继承、块标签:
<td class ="sale">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png">
        <h1 class="description">ОписаниеОписаниеОписаниеОписание</h1>
  <a class="buy" href="#openModal" >
    <span >Купить</span></a>
  <h1 class="price">цена</h1>
  </td>
  1. 修改Homepage/index.html,删掉原有的include sale.html的代码:
{% block sale %}
<!-- 如果需要index直接展示sale内容,保留下面这行,否则留空即可 -->
{% include "articles/sale_fragment.html" %}
{% endblock %}
  1. 修改sale.html,通过引入公共片段复用代码:
{% extends "Homepage/index.html" %}
{% block sale %}
{% include "articles/sale_fragment.html" %}
{% endblock %}

方案2:仅需要在index页面展示sale内容,不需要单独的sale路由页面

直接修改sale.html,删除第一行的继承语句和block标签,仅保留业务代码即可:

<td class ="sale">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png">
        <h1 class="description">ОписаниеОписаниеОписаниеОписание</h1>
  <a class="buy" href="#openModal" >
    <span >Купить</span></a>
  <h1 class="price">цена</h1>
  </td>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:36:08