Django项目中分类与标签无法动态显示的修复方案咨询
问题排查与修复方案
1. 分类不显示:模板与视图变量名不匹配
模板里循环分类的代码写的是{% for category in categorys %},但所有视图向模板传递的分类变量名是categories(正确复数拼写),变量名不一致导致模板找不到数据。
修复:修改模板中的循环变量名:
{% for category in categories %} <li><a href="{% url 'topic_by_category' category.slug %}">{{category.name}}</a></li> {% endfor %}
2. 标签不显示:变量名单复数错误
所有视图向模板传递标签数据时,用的是单数变量名tag,但模板里循环标签用的是复数tags,变量名不匹配导致无数据渲染。
修复:修改所有视图的context中标签的变量名(以topic_list为例,其余视图同理):
context = { 'topics' : topics, 'categories' : categories, 'tags' : tags # 把原本的'tag'改成'tags' }
3. 标签列表逻辑错误:调用了错误的模型
tag_list视图里,错误地把标签数据查询写成了tags = Category.objects.all(),实际应该调用Tag模型。
修复:修正标签查询代码:
def tag_list(request, tag_slug,): topics= Topic.objects.all().filter(tag__slug = tag_slug) categories = Category.objects.all() tags = Tag.objects.all() # 把Category改成Tag context = { 'topics' : topics, 'categories' : categories, 'tags' : tags # 同步把变量名改成复数 } return render(request, 'topics.html', context)
4. 详情页侧边栏无分类/标签:未传递对应数据
topic_detail视图的context里只传了topics,没有传递分类和标签数据,导致详情页侧边栏的分类、标签模块无内容。
修复:补充详情页的context数据:
def topic_detail(request, topic_slug, topic_id): topics = Topic.objects.get(category__slug = topic_slug, id = topic_id) categories = Category.objects.all() tags = Tag.objects.all() context = { 'topics' : topics, 'categories' : categories, 'tags' : tags } return render(request, 'topic.html', context)
5. 可选修复:Admin配置拼写错误
TopicAdmin里的listfield是拼写错误,应该为fields,同时desciription也是拼写错误,修正后不影响前端显示,但能保证Admin配置正常:
@admin.register(Topic) class TopicAdmin(admin.ModelAdmin): list_display = ("name", "available") list_filter = ("available",) fields = ("name", "description") # 修正拼写错误
内容的提问来源于stack exchange,提问作者H. Kürşat AKBURAK
相关产品推荐
相关产品推荐

