标签

Wagtail 通过组合两个 Django 模块来提供标签功能。

  1. django-taggit - 提供一套通用的标签实现。

  2. django-modelcluster - 扩展了 django-taggit 的 TaggableManager,使标签关系可以在内存中管理而无需写入数据库,这是处理预览和修订版本所必需的。

为页面模型添加标签

要为页面模型添加标签,你需要定义一个继承 TaggedItemBase 的'through'模型,用于建立 django-taggit 的 Tag 模型与你的页面模型之间的多对多关系,并在页面模型上添加 ClusterTaggableManager 访问器,把该关系表现为单个标签字段。

在这个示例中,我们通过 BlogPageTag 模型为 BlogPage 设置标签功能:

# models.py

from modelcluster.fields import ParentalKey
from modelcluster.contrib.taggit import ClusterTaggableManager
from taggit.models import TaggedItemBase

class BlogPageTag(TaggedItemBase):
    content_object = ParentalKey('demo.BlogPage', on_delete=models.CASCADE, related_name='tagged_items')

class BlogPage(Page):
    ...
    tags = ClusterTaggableManager(through=BlogPageTag, blank=True)

    promote_panels = Page.promote_panels + [
        ...
        FieldPanel('tags'),
    ]

Wagtail 的管理后台为内容标签输入提供了友好的界面,支持即时补全(typeahead)标签和友好的标签图标。

现在我们可以在视图和模板中利用这种多对多标签关系。例如,我们可以让博客索引页接受 ?tag=... 查询参数,以便按标签筛选 BlogPage 列表:

from django.shortcuts import render


class BlogIndexPage(Page):
    ...

    def get_context(self, request):
        context = super().get_context(request)

        # 获取博客条目
        blog_entries = BlogPage.objects.child_of(self).live()

        # 按标签筛选
        tag = request.GET.get("tag")
        if tag:
            blog_entries = blog_entries.filter(tags__name=tag)

        context["blog_entries"] = blog_entries
        return context

这里,blog_entries.filter(tags__name=tag) 顺着 BlogPage 上的 tags 关系,在把列表传给模板渲染之前,只保留那些标签名匹配的页面。现在我们可以更新 blog_page.html 模板,显示与页面关联的标签列表,并提供回到筛选后索引页的链接:

{% for tag in page.tags.all %}
    <a href="{% pageurl page.blog_index %}?tag={{ tag }}">{{ tag }}</a>
{% endfor %}

遍历 page.tags.all 会显示与 page 关联的每个标签,而回到索引页的链接则利用了添加到 BlogIndexPage 模型的筛选选项。Django 查询也可以使用 tagged_items 这个关联名来获取与某个标签关联的 BlogPage 对象。

同样的做法也可用于为通过 Snippet 管理的非页面模型添加标签。此时该模型必须继承 modelcluster.models.ClusterableModel,才能与 ClusterTaggableManager 兼容。

自定义标签模型

在上面的示例中,新建的任何标签都会加到 django-taggit 的默认 Tag 模型中,而该模型会被所有使用同一做法的其他模型以及 Wagtail 的图片和文档模型共享。特别是,这意味着标签字段上的自动补全建议会包含先前添加到其他模型的标签。要避免这一点,你可以建立一个继承 TagBase 的自定义标签模型,以及一个继承 ItemBase 的'through'模型,从而为该页面模型提供独立的标签池。

from django.db import models
from modelcluster.contrib.taggit import ClusterTaggableManager
from modelcluster.fields import ParentalKey
from taggit.models import TagBase, ItemBase


class BlogTag(TagBase):
    class Meta:
        verbose_name = "blog tag"
        verbose_name_plural = "blog tags"


class TaggedBlog(ItemBase):
    tag = models.ForeignKey(
        BlogTag, related_name="tagged_blogs", on_delete=models.CASCADE
    )
    content_object = ParentalKey(
        to="demo.BlogPage", on_delete=models.CASCADE, related_name="tagged_items"
    )


class BlogPage(Page):
    ...
    tags = ClusterTaggableManager(through="demo.TaggedBlog", blank=True)

在管理后台中,标签字段会自动识别所使用的自定义标签模型,并提供取自该标签模型的自动补全建议。

禁用自由打标签

默认情况下,标签字段按“自由打标签”方式工作:编辑者可以在字段中输入任何内容,保存时凡是未被识别为已有标签的文本都会被自动创建。要禁用该行为、只允许编辑者输入数据库中已存在的标签,自定义标签模型可接受 free_tagging = False 选项:

from taggit.models import TagBase
from wagtail.snippets.models import register_snippet


@register_snippet
class BlogTag(TagBase):
    free_tagging = False

    class Meta:
        verbose_name = "blog tag"
        verbose_name_plural = "blog tags"

这里我们把 BlogTag 注册为 Snippet,为管理员(以及其他具有相应权限的用户)提供一个管理允许标签集的界面。设置 free_tagging = False 选项后,编辑者无法再向标签字段输入任意文本,而必须从自动补全下拉列表中选择已有标签。

以 Snippet 方式管理标签

要管理项目中使用的所有标签,你可以把 Tag 模型注册为 Snippet,通过 Wagtail 管理后台管理。这样你就能在主菜单中获得一个标签管理界面,可在其中添加、编辑或删除标签。

从内容中移除的标签不会被从 Tag 模型中删除,仍会出现在即时补全标签建议中。因此拥有一个标签管理界面是彻底清除不需要标签的好办法。

要添加标签管理界面,请把以下代码块添加到项目任一应用的 wagtail_hooks.py 文件中:

from wagtail.admin.panels import FieldPanel
from wagtail.snippets.models import register_snippet
from wagtail.snippets.views.snippets import SnippetViewSet
from taggit.models import Tag


class TagsSnippetViewSet(SnippetViewSet):
    panels = [FieldPanel("name")]  # 只显示名称字段
    model = Tag
    icon = "tag"  # 按需更改
    add_to_admin_menu = True
    menu_label = "Tags"
    menu_order = 200  # 将排在第三位(000 为第一,100 为第二)
    list_display = ["name", "slug"]
    search_fields = ("name",)


register_snippet(TagsSnippetViewSet)

Tag 模型有 name 和 slug 两个必填字段。如果你决定添加标签,建议只显示 name 字段面板,因为填写 name 字段时 slug 字段会自动填充,你无需在两个字段中重复输入相同的名称。