Wagtail是支援Django的tag功能django-taggit的
首先我們先來更新models.py
from taggit.models import TaggedItemBase, Tag as TaggitTag
class BlogPageTag(TaggedItemBase):
    content_object = ParentalKey('PostPage', related_name='post_tags')
@register_snippet
class Tag(TaggitTag):
    class Meta:
        proxy = True
在這裏,我們引入了TaggedItemBase讓我們對tag的目標進行自定義,一般來說,在Django裡面使用taggit,code應該會是content_object = models.ForeignKey('PostPage')。在Wagtail我們使用ParentalKey代替ForeignKey。
為了使我們能夠管理標籤snippet,我們將Tag設置為taggit包中Tag的代理。接著我們要在PostPage中新增tags的欄位。
from modelcluster.fields import ParentalKey, ParentalManyToManyField
from modelcluster.tags import ClusterTaggableManager
class PostPage(Page):
    body = RichTextField(blank=True)
    categories = ParentalManyToManyField('blog.BlogCategory', blank=True)
    tags = ClusterTaggableManager(through='blog.BlogPageTag', blank=True)
    content_panels = Page.content_panels + [
        FieldPanel('body', classname="full"),
        FieldPanel('categories', widget=forms.CheckboxSelectMultiple),
        FieldPanel('tags'),
    ]
ClusterTaggableManager可以控制tags之間的關係,然後我們用FieldPanel('tag')把tags的選項放到content_panels裡面。
同樣的,進行migrations
python manage.py makemigrations
python manage.py migrate
接著我們就可以在後台的blog_page新增tags

接著修改blog_page.html
{% if page.tags.all.count %}
    <div class="tags">
        <h3>Tags</h3>
        {% for tag in page.tags.all %}
            <button type="button">{{ tag }}</button>
        {% endfor %}
    </div>
{% endif %}
{% with categories=page.categories.all %}
    {% if categories %}
        <h3>Categories</h3>
        <ul>
            {% for category in categories %}
                <li style="display: inline">
                    {{ category.name }}
                </li>
            {% endfor %}
        </ul>
    {% endif %}
{% endwith %}
這樣,我們就可以看到tags和categories顯示在blog_page的頁面裡了~~