使用多词标签时django-taggit触发404错误的问题求助
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 theirnameandslugare identical (e.g., tag "Python" has slug "python"), but multi-word tags have a slug likedesign-thinkingthat doesn’t match the original nameDesign 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 theslugconverter (thoughstrworks 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

