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

Wagtail侧边栏传递tags时post_by_tag路由反向解析错误如何解决

问题根因

报错核心原因是生成路由时传递的tag.slug为空字符串,匹配不上路由要求的[-\w]+规则,存在3处可直接修复的代码问题:

  • templatetags.py中变量名写错:painting_tags_list函数查询到的标签存到了painting_tags变量,但返回给模板的是未定义的tags变量,属于隐藏bug
  • 部分Tag实例的slug字段为空:Tag模型继承自Taggit的TaggitTag,默认slug自动生成,但手动创建未填充slug、或老数据未生成slug都会出现空值
  • 上下文依赖不合理:如果非详情/索引页也使用了侧边栏,默认不会携带painting_index_page上下文,会导致路由生成异常

修复步骤

  1. 修正templatetags.py代码
@register.inclusion_tag("catalog/components/painting_tags_list.html", takes_context=True)
def painting_tags_list(context):
    page = context["page"]
    # 修正related_name对应的属性名,修正返回的变量名
    painting_tags = page.post_tags.all()
    return {
        "request": context["request"],
        "tags": painting_tags,
    }

@register.inclusion_tag('catalog/components/tags_list.html', takes_context=True)
def tags_list(context):
    tags = Tag.objects.all()
    # 主动获取索引页实例,不依赖上下文传递
    from catalog.models import PaintingIndexPage
    painting_index_page = PaintingIndexPage.objects.first()
    return {
        'request': context['request'],
        'painting_index_page': painting_index_page,
        'tags': tags
    }
  1. 给标签渲染添加空slug过滤,避免无效标签参与渲染
    在tags_list.html和painting_tags_list.html的循环逻辑中添加判断:
{% for tag in tags %}
  {% if tag.slug %}
    <li>
      <a href="{% routablepageurl painting_index_page "post_by_tag" tag.slug %}" class="text-decoration-none">
        <span class="badge bg-secondary">{{ tag }}</span>
      </a>
    </li>
  {% endif %}
{% endfor %}
  1. 批量补全现有Tag的slug值
    进入Django shell执行以下代码自动生成缺失的slug:
from catalog.models import Tag
for tag in Tag.objects.all():
    if not tag.slug:
        tag.save() # 触发taggit内置的slug自动生成逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 12:54:01