diff --git a/district/wagtail_hooks.py b/district/wagtail_hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..07ae0e6bb082420737315f50b17f2ba9533a51b8 --- /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)