From 675d3f38b9a8a3b305b76aff542446e02be6ef28 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Wed, 20 Jul 2022 08:41:40 +0100 Subject: [PATCH] Ensure tags menu item works when the list page doesn't exist --- website/blog/wagtail_hooks.py | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/website/blog/wagtail_hooks.py b/website/blog/wagtail_hooks.py index 891babb..3baa9dc 100644 --- a/website/blog/wagtail_hooks.py +++ b/website/blog/wagtail_hooks.py @@ -1,3 +1,4 @@ +from django.http.request import HttpRequest from django.urls import reverse from wagtail import hooks from wagtail.admin.menu import MenuItem @@ -5,15 +6,28 @@ from wagtail.admin.menu import MenuItem from .models import BlogPostTagListPage +class BlogPostTagsMenuItem(MenuItem): + url: str + + def __init__(self) -> None: + super().__init__("Blog post tags", url="", icon_name="tag") + + def is_shown(self, request: HttpRequest) -> bool: + if not self.url: + blog_post_tag_list_id = ( + BlogPostTagListPage.objects.live() # type:ignore[attr-defined] + .values_list("id", flat=True) + .first() + ) + self.url = ( + reverse("wagtailadmin_explore", args=[blog_post_tag_list_id]) + if blog_post_tag_list_id + else "" + ) + + return bool(self.url) + + @hooks.register("register_admin_menu_item") def register_blog_post_tags_menu_item() -> MenuItem: - blog_post_tag_list_id = ( - BlogPostTagListPage.objects.live() # type:ignore[attr-defined] - .values_list("id", flat=True) - .get() - ) - return MenuItem( - "Blog post tags", - reverse("wagtailadmin_explore", args=[blog_post_tag_list_id]), - icon_name="tag", - ) + return BlogPostTagsMenuItem()