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

Django自定义range模板过滤器无法生效,求问题排查与解决

问题排查与修复方案

核心问题及解决步骤:

1. 模板标签包未正确配置

templatetags 文件夹必须是合法的Python包,你需要在该文件夹下添加空的__init__.py文件,否则Django无法识别自定义过滤器。

2. 函数名与内置range冲突

你的过滤器函数命名为range,会覆盖Python内置的range函数,导致函数内部调用自身引发无限递归(这就是页面报错的直接原因)。修复方式二选一:

方案A:重命名过滤器函数

from django import template

register = template.Library()

@register.filter(name='range')  # 保留模板中使用的过滤器名称为range
def custom_range(start, end):
    return range(start, end + 1)

方案B:导入内置range并使用别名

from django import template
from builtins import range as builtin_range

register = template.Library()

@register.filter
def range(start, end):
    return builtin_range(start, end + 1)

3. 模板未加载自定义过滤器

在使用过滤器的模板顶部,必须添加加载语句:

{% load custom-filters %}  # 文件名是custom-filters.py,所以用这个名称加载

<br>
<table>
    <thead>
      <tr>
        <th>Revenue streams</th>
        <th>Units</th>
        <th>Description</th>
        {% for num in 2022|range:2027 %}
          <th>{{ num }}</th>
        {% endfor %}
      </tr>
</thead>
</table>

4. 确认应用已加入INSTALLED_APPS

在项目的settings.py中,确保包含自定义过滤器的应用已被添加:

INSTALLED_APPS = [
    # ... 其他应用
    '你的应用名称',
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 17:22:45