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

使用多词标签时django-taggit触发404错误的问题求助

Fixing Multi-Word Tag 404 Errors with Taggit & Bakery-Demo

Hey there, let’s work through this multi-word tag 404 issue—this is a super common gotcha with taggit, so I’ve got a few solid leads for you:

  • Check your view’s tag query (most likely culprit)
    Single-word tags work because their name and slug are identical (e.g., tag "Python" has slug "python"), but multi-word tags have a slug like design-thinking that doesn’t match the original name Design Thinking. If your view is using:

    tag = get_object_or_404(Tag, name=tag_slug)
    

    That’s the problem! Swap it to query by slug instead:

    tag = get_object_or_404(Tag, slug=tag_slug)
    

    This explains why the bakery-demo has the same issue—its code probably uses the name instead of slug for the lookup.

  • Verify template URL links
    Make sure you’re passing the tag’s slug (not its name) when generating links in templates. A common mistake is:

    <!-- Wrong: Passes the name with spaces, which gets URL-encoded incorrectly -->
    <a href="{% url 'tagged-items' tag.name %}">{{ tag.name }}</a>
    

    Replace it with:

    <!-- Correct: Uses the slug that matches your route -->
    <a href="{% url 'tagged-items' tag.slug %}">{{ tag.name }}</a>
    
  • Confirm your URL route uses the right parameter converter
    Your route should use the slug converter (though str works too, since slugs only use letters, numbers, hyphens, and underscores) to capture the tag slug:

    path('tags/<slug:tag_slug>/', TagListView.as_view(), name='tagged-items'),
    

    This ensures the full slug (including hyphens) is captured correctly.

  • Double-check tag slug generation
    If you’re using a custom Tag model instead of taggit’s default, make sure the slug auto-generates from the name. The default taggit Tag handles this automatically, but if you’ve extended it, confirm your save method includes slugification:

    from taggit.models import Tag
    from django.utils.text import slugify
    
    class CustomTag(Tag):
        def save(self, *args, **kwargs):
            if not self.slug:
                self.slug = slugify(self.name)
            super().save(*args, **kwargs)
    

Give these steps a shot—9 times out of 10, this is just a mix-up between the tag’s name and slug fields. Let me know if you need help digging into the bakery-demo code to fix it there too!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:00:13