gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:30:05 25 4
gpt4 key购买 nike

我见过这个:

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 %}

救命!感觉这个事情不应该这么复杂。谢谢

最佳答案

您可以在新的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 演示的 blog_index_page.html 中查看类似的模板方法

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

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

关于python - Django/Wagtail/taggit - 获取模型特定的标签列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355220/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com