From cf05d212061940943539a814413683748444f105 Mon Sep 17 00:00:00 2001 From: Struan Donald Date: Thu, 15 Feb 2024 10:51:11 +0000 Subject: [PATCH] handle lower case area names and redirect to canonical URL Again, in case someone lower cases the area name check for this and redirect to the canonical URL --- hub/tests/test_views.py | 7 +++++++ hub/views/area.py | 15 +++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/hub/tests/test_views.py b/hub/tests/test_views.py index 3fcb4cda3..aa3d5b2c9 100644 --- a/hub/tests/test_views.py +++ b/hub/tests/test_views.py @@ -214,6 +214,13 @@ def test_area_page_lower_case_area_code(self): self.assertEqual(response.status_code, 301) self.assertEqual(response.headers["Location"], "/area/WMC/South%20Borsetshire") + def test_area_page_lower_case_area_name(self): + url = reverse("area", args=("wmc", "south borsetshire")) + response = self.client.get(url) + + self.assertEqual(response.status_code, 301) + self.assertEqual(response.headers["Location"], "/area/WMC/South%20Borsetshire") + def test_area_page_logged_in(self): DataSet.objects.update(featured=True) url = reverse("area", args=("WMC", "South Borsetshire")) diff --git a/hub/views/area.py b/hub/views/area.py index ded321a61..ff6561901 100644 --- a/hub/views/area.py +++ b/hub/views/area.py @@ -39,12 +39,12 @@ class BaseAreaView(TitleMixin, DetailView): def get_object(self): area_type_code = self.kwargs.get("area_type", "") - lower_case_code = False + bad_case = False if area_type_code not in AreaType.VALID_AREA_TYPES: area_type_code = area_type_code.upper() if area_type_code in AreaType.VALID_AREA_TYPES: - lower_case_code = True + bad_case = True try: area = Area.objects.get( @@ -52,9 +52,16 @@ def get_object(self): name=self.kwargs.get("name"), ) except Area.DoesNotExist: - raise Http404("Area not found") + try: + area = Area.objects.get( + area_type__code=area_type_code, + name__iexact=self.kwargs.get("name"), + ) + bad_case = True + except Area.DoesNotExist: + raise Http404("Area not found") - if lower_case_code: + if bad_case: return redirect(area, permanent=True) return area