本文介绍了在Wagtail中生成Django-Taggit标签的唯一列表;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Wagtail博客索引页面的边栏中添加类别标签列表。下面的代码可以正常工作,但是不幸的是,它遍历了帖子,并将所有标签作为单独的标签列出,最终我得到了重复的标签。我是根据Wagtail演示创建博客的,因为它不像以前那样使用Views,所以不确定在哪里添加.distinct('tags')。

I am trying to add a list of category tags in the sidebar of my Wagtail blog index page. The code below does work, but unfortunately it iterates through the posts and lists all the tags as individual tags, which I ultimately end up with duplicate tags. I built my blog from the Wagtail demo and since it doesn't use Views like I am used to, I am not sure where to add .distinct('tags').

模板

{% for b in blogs %}
  {% for tag in b.tags.all %}
    <li><a href="{% pageurl b.blog_index %}?tag={{ tag }}" class="btn btn-primary btn-xs"> <i class="glyphicon glyphicon-tag"></i> {{ tag }}<span>{{ tag }}</span></a>
       {% if not forloop.last %} {% endif %}
   </li>
 {% endfor %}
{% endfor %}


推荐答案

通常会在视图函数中使用的任何逻辑都可以进入页面模型的 get_context 方法:

Any logic that would normally go in a view function, can go in the page model's get_context method:

from django.contrib.contenttypes.models import ContentType
from taggit.models import Tag

class BlogIndex(Page):
    # ...
    def get_context(self, request):
        context = super(BlogIndex, self).get_context(request)

        blog_content_type = ContentType.objects.get_for_model(BlogPage)
        context['tags'] = Tag.objects.filter(
            taggit_taggeditem_items__content_type=blog_content_type
        )

        return context

(此处的标签获取代码改编自。 )

(the tag-fetching code here is adapted from some internal Wagtail code.)

这篇关于在Wagtail中生成Django-Taggit标签的唯一列表;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 08:47