djangowagtaildjango-taggit

How to seperate wagtail image's tags from page's tags?


Suppose we have a wagtail page defined like this:

class PostTag(TaggedItemBase):
    content_object = ParentalKey(
        'PostPage',
        related_name='tagged_items',
        on_delete=models.CASCADE
    )


class PostPage(Page):
    ...
    tags = ClusterTaggableManager(through=PostTag, blank=True)
    ...

    content_panels = Page.content_panels + [
        ...
        FieldPanel('tags')
    ]

When I want to edit tags field on wagtail admin, it suggests not only pages' tags but also images' tags. I want to some how remove images' tags from suggestions.

In my project, pages' tags are not related to image's tags.

To understand the scenario, look at these two pictures:

enter image description here

I don't want to see the river tag as a suggestion on page's tags: enter image description here

Is that possible? If not, Is it possible to remove tags field from wagtail image model?


Solution

  • You can do this by setting up a custom Tag model that extends from taggit.models.TagBase. This is then handled as a distinct model from the default Tag model used for images and documents.

    from django.db import models
    from modelcluster.contrib.taggit import ClusterTaggableManager
    from modelcluster.fields import ParentalKey
    from taggit.models import TagBase, ItemBase
    
    class PostTag(TagBase):
        class Meta:
            verbose_name = "post tag"
            verbose_name_plural = "post tags"
    
    
    class TaggedPost(ItemBase):
        tag = models.ForeignKey(
            PostTag, related_name="tagged_posts", on_delete=models.CASCADE
        )
        content_object = ParentalKey(
            to='myapp.PostPage',
            on_delete=models.CASCADE,
            related_name='tagged_items'
        )
    
    class PostPage(Page):
        ...
        tags = ClusterTaggableManager(through=TaggedPost, blank=True)
    

    In this example, PostTag is the custom tag model, and TaggedPost is the link table that relates tags to posts (the equivalent of PostTag in your code).