Django / Wagtail / taggit - 获取模型特定标签列表

时间:2017-11-17 16:31:04

标签: python html django wagtail django-taggit

我见过这个:

Generating a unique list of Django-Taggit Tags in Wagtail;

并且那里的解决方案生成了所有存储标签的列表,即图像,文档等标签。

我正在努力实现类似的目标。在新闻索引页面上,下载新闻页面标签。

我似乎无法获得仅包含新闻页面标记的标记列表,目前这会为我提供网站中所有标记的列表,包括图像和文档标记。

from django.template.response import TemplateResponse
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.tags import ClusterTaggableManager
from taggit.models import TaggedItemBase, Tag
from core.models import Page

class NewsPageTag(TaggedItemBase):
    content_object = ParentalKey('NewsPage', related_name='tagged_items')


class NewsPage(Page):
    tags = ClusterTaggableManager(through=NewsPageTag, blank=True)


class NewsIndexPage(Page):

    def serve(self, request, *args, **kwargs):
        context['tags'] = Tag.objects.all().distinct('taggit_taggeditem_items__tag')
        return TemplateResponse(
            request,
            self.get_template(request, *args, **kwargs),
            context
        )

我也尝试过:

from django.contrib.contenttypes.models import ContentType
# ...
def serve(self, request, *args, **kwargs):
    news_content_type = ContentType.objects.get_for_model(NewsPage)
    context['tags'] = Tag.objects.filter(
        taggit_taggeditem_items__content_type=news_content_type
    )
    return TemplateResponse(
        request,
        self.get_template(request, *args, **kwargs),
        context
    )

context['tags']分配为空集

我的模板:

{% if tags.all.count %}
    {% for tag in tags.all %}
        <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a>
    {% endfor %}
{% endif %}

HELP!这感觉不应该这么复杂。谢谢

1 个答案:

答案 0 :(得分:1)

您可以在新的Wagtail Bakery Demo application中复制这是如何实现的,这是一个很好的参考。

基本上只需获取所有子页面,然后使用set获取标记,以确保它们是唯一对象。

首先向NewsIndexPage添加一种方法,以帮助您以一致的方式获取这些标记。

See: models.py

class NewsIndexPage(Page):

    # Returns the list of Tags for all child posts of this BlogPage.
    def get_child_tags(self):
        tags = []
        news_pages = NewsPage.objects.live().descendant_of(self);
        for page in news_pages:
            # Not tags.append() because we don't want a list of lists
            tags += page.get_tags
        tags = sorted(set(tags))
        return tags

因为你的NewsPageIndex模型有一个方法,你不需要覆盖serve方法,你可以直接在模板中获取标签。

    {% if page.get_child_tags %}
        {% for tag in page.get_child_tags %}
            <a class="dropdown-item" href="?tag={{ tag.id }}">{{ tag }}</a>
        {% endfor %}
    {% endif %}

在Wagtail Bakery Demo&#39; s blog_index_page.html

中查看类似的模板方法

注意:您仍然可以通过serve方法执行此类操作来添加上下文:

context['tags'] = self.get_child_tags()