wagtailwagtail-snippet

Linking bewteen BlogPost and Category not working in Wagtail


I was following this tutorial to add blog to wagtail. below are my codes;

class PostDetail(Page):
    template = "Post_Detail.html"
    
    body = RichTextField(blank=True)
    
    tags = ClusterTaggableManager(through="Link_PostDetail_Tag", blank=True)

    search_fields = Page.search_fields + [
        index.SearchField("body"),
    ]

    content_panels = Page.content_panels + [
        FieldPanel("body"),
        InlinePanel("rn_category", label="label_category"),     
        FieldPanel("tags"),
    ]

    parent_page_type = [
        "PostList",
    ]

    subpage_types = []      # Disable "Add CHILD PAGE"

@register_snippet
class Category(models.Model):
    name = models.CharField(max_length=255)
    slug = models.SlugField(unique=True, max_length=100)

    panels = [
        FieldPanel("name"),
        FieldPanel("slug"),
    ]

    def __str__(self):
        return self.name

    class Meta:
        verbose_name = "Category"
        verbose_name_plural = "Categories"


@register_snippet
class Tag(TaggitTag):
    class Meta:
        proxy = True

class Link_PostDetail_Category(models.Model):
    page = ParentalKey(
        "PostDetail", on_delete = models.CASCADE, related_name="rn_category"
    )

    category = models.ForeignKey(
        "Category", on_delete = models.CASCADE, related_name="rn_post_detail"
    )

    panels = [
        SnippetChooserPanel("category"),
    ]

    class Meta:
        unique_together = ("page", "category")


class Link_PostDetail_Tag(TaggedItemBase):
    content_object = ParentalKey("PostDetail", related_name="rn_tags", on_delete=models.CASCADE)

After DB migration, I can see the relation table between PostDetail and Category already created.

enter image description here

However, during my debugging via PDB (PostDetail class is direct child of PostList class), I am not able to link to Category from PostDetail. Anything wrong ?

(Pdb++) pp obj.get_children
<bound method MP_Node.get_children of <PostList: Post List>>
(Pdb++) whatis obj.get_children()
<class 'wagtail.core.query.PageQuerySet'>
(Pdb++) whatis obj.get_children()[0]
<class 'wagtail.core.models.Page'>
(Pdb++) pp obj.get_children()[0].__dict__     # I did  not see 'rn_category' attribute in the output. 

(Pdb++) whatis obj.get_children()[0].rn_category.all
*** AttributeError: 'Page' object has no attribute 'rn_category'

Solution

  • The rn_category relation is defined on the PostDetail model, but the object you retrieved from get_children is an instance of Page (which only has the core fields and methods such as title available). To retrieve the full PostDetail object, use .specific:

    obj.get_children()[0].specific.rn_category.all
    

    More details on specific here: https://docs.wagtail.io/en/stable/topics/pages.html#working-with-pages