From 8d724277b07dfb4f3e086144cccdbbea87449554 Mon Sep 17 00:00:00 2001 From: Jake Howard Date: Thu, 9 May 2024 19:42:33 +0100 Subject: [PATCH] Add random button to listing pages --- website/blog/templates/blog/blog_post_list_page.html | 2 -- website/common/models.py | 7 +++++++ website/common/templates/common/listing_page.html | 4 +++- website/common/tests/test_pages.py | 9 +++++++++ 4 files changed, 19 insertions(+), 3 deletions(-) diff --git a/website/blog/templates/blog/blog_post_list_page.html b/website/blog/templates/blog/blog_post_list_page.html index 9a8b717..29bbd13 100644 --- a/website/blog/templates/blog/blog_post_list_page.html +++ b/website/blog/templates/blog/blog_post_list_page.html @@ -1,7 +1,5 @@ {% extends "common/listing_page.html" %} -{% load wagtailroutablepage_tags %} - {% block hero_buttons %} {{ block.super }} diff --git a/website/common/models.py b/website/common/models.py index e8c1be5..cfb24ab 100644 --- a/website/common/models.py +++ b/website/common/models.py @@ -295,6 +295,13 @@ class BaseListingPage(RoutablePageMixin, BaseContentPage): def feed(self, request: HttpRequest) -> HttpResponse: return redirect("feed", permanent=True) + @route(r"^random/$") + def random(self, request: HttpRequest) -> HttpResponse: + page = self.get_listing_pages().order_by("?").first() + if page is None: + return redirect(self.get_url(request=request), permanent=False) + return redirect(page.get_url(request=request), permanent=False) + class ListingPage(BaseListingPage): pass diff --git a/website/common/templates/common/listing_page.html b/website/common/templates/common/listing_page.html index 3bda7cf..2b9f656 100644 --- a/website/common/templates/common/listing_page.html +++ b/website/common/templates/common/listing_page.html @@ -1,8 +1,10 @@ {% extends "common/content_page.html" %} -{% load wagtailadmin_tags %} +{% load wagtailadmin_tags wagtailroutablepage_tags %} {% block hero_buttons %} + + {% if listing_pages.has_previous %} {% endif %} diff --git a/website/common/tests/test_pages.py b/website/common/tests/test_pages.py index e4eb406..2bc3a13 100644 --- a/website/common/tests/test_pages.py +++ b/website/common/tests/test_pages.py @@ -77,3 +77,12 @@ class ListingPageTestCase(TestCase): self.assertEqual( response.context["page"].get_meta_url(), self.page.full_url + "?page=2" ) + + def test_random(self) -> None: + url = self.page.url + self.page.reverse_subpage("random") + with self.assertNumQueries(10): + response = self.client.get(url) + self.assertEqual(response.status_code, 302) + self.assertIn( + response.url, [page.get_url() for page in self.page.get_listing_pages()] + )