From 23b2218f53b6c1ad6253dae148ed51232145f3ba Mon Sep 17 00:00:00 2001
From: OndraRehounek <ondra.rehounek@seznam.cz>
Date: Fri, 4 Mar 2022 10:44:49 +0100
Subject: [PATCH] district and region: Page chooser hook filtering parents only
 - concept version

---
 district/wagtail_hooks.py | 46 +++++++++++++++++++++++++++++++++++++++
 1 file changed, 46 insertions(+)
 create mode 100644 district/wagtail_hooks.py

diff --git a/district/wagtail_hooks.py b/district/wagtail_hooks.py
new file mode 100644
index 00000000..07ae0e6b
--- /dev/null
+++ b/district/wagtail_hooks.py
@@ -0,0 +1,46 @@
+import re
+
+from wagtail.core import hooks
+
+# FIXME hooks are loaded globally so it doesn't make sense to have it in this module
+
+
+@hooks.register("construct_page_chooser_queryset")
+def this_web_only(pages, request):
+    add_result = re.search(
+        "page/(.*)/", request.META.get("HTTP_REFERER")
+    )  # FIXME better regex
+    edit_result = re.search("pages/(.*)/edit", request.META.get("HTTP_REFERER"))
+
+    if add_result:
+        return handle_add_page_selection(pages=pages, add_result=add_result)
+
+    if edit_result:
+        return handle_edit_page_selection(pages=pages, edit_result=edit_result)
+
+    return pages
+
+
+def handle_add_page_selection(pages, add_result):
+    parent_page_id = add_result.group(1)
+    if parent_page_id == 1:  # pro novou homepage žádné podstránky nejsou
+        return pages.none()
+
+    parent_page = pages.model.objects.get(id=parent_page_id)
+    root_page = getattr(parent_page.specific, "root_page", None)
+    return get_only_root_page_descendants(pages=pages, root_page=root_page)
+
+
+def handle_edit_page_selection(pages, edit_result):
+    current_page_id = edit_result.group(1)
+    current_page = pages.model.objects.get(id=current_page_id)
+    root_page = getattr(current_page.specific, "root_page", None)
+    return get_only_root_page_descendants(pages=pages, root_page=root_page)
+
+
+def get_only_root_page_descendants(pages, root_page):
+    if not root_page:
+        return pages
+
+    web_pages_id_list = root_page.get_descendants().live().values_list("id", flat=True)
+    return pages.filter(id__in=web_pages_id_list)
-- 
GitLab