From e7312a429d44cefdcf47efaf89428b89448ba68c Mon Sep 17 00:00:00 2001 From: Karl Hobley Date: Thu, 26 Oct 2017 09:51:08 +0100 Subject: [PATCH] Fix AttributeError in listing_view endpoint Fixes #3967 If there was no site configured, the listing views in the API would break with an AttributeError. Now, the following happens if there is no site record: - In the Admin API, all pages are returned but links in the response do not include a domain name - In the Public API, no pages are returned --- wagtail/api/v2/endpoints.py | 6 +++++- wagtail/api/v2/tests/test_pages.py | 10 +++++++++- wagtail/api/v2/utils.py | 2 +- 3 files changed, 15 insertions(+), 3 deletions(-) diff --git a/wagtail/api/v2/endpoints.py b/wagtail/api/v2/endpoints.py index a9bffca0a9..b2b08760bb 100644 --- a/wagtail/api/v2/endpoints.py +++ b/wagtail/api/v2/endpoints.py @@ -396,7 +396,11 @@ class PagesAPIEndpoint(BaseAPIEndpoint): queryset = queryset.public().live() # Filter by site - queryset = queryset.descendant_of(request.site.root_page, inclusive=True) + if request.site: + queryset = queryset.descendant_of(request.site.root_page, inclusive=True) + else: + # No sites configured + queryset = queryset.none() return queryset diff --git a/wagtail/api/v2/tests/test_pages.py b/wagtail/api/v2/tests/test_pages.py index a65b6083a7..c2985d74e5 100644 --- a/wagtail/api/v2/tests/test_pages.py +++ b/wagtail/api/v2/tests/test_pages.py @@ -11,7 +11,7 @@ from django.urls import reverse from wagtail.api.v2 import signal_handlers from wagtail.tests.demosite import models from wagtail.tests.testapp.models import StreamPage -from wagtail.wagtailcore.models import Page +from wagtail.wagtailcore.models import Page, Site def get_total_page_count(): @@ -753,6 +753,14 @@ class TestPageListing(TestCase): self.assertEqual(response['Content-type'], 'application/json') self.assertEqual(content['meta']['total_count'], 0) + # REGRESSION TESTS + + def test_issue_3967(self): + # The API crashed whenever the listing view was called without a site configured + Site.objects.all().delete() + response = self.get_response() + self.assertEqual(response.status_code, 200) + class TestPageDetail(TestCase): fixtures = ['demosite.json'] diff --git a/wagtail/api/v2/utils.py b/wagtail/api/v2/utils.py index 273996a20f..dab84c3db6 100644 --- a/wagtail/api/v2/utils.py +++ b/wagtail/api/v2/utils.py @@ -12,7 +12,7 @@ class BadRequestError(Exception): def get_base_url(request=None): - base_url = getattr(settings, 'WAGTAILAPI_BASE_URL', request.site.root_url if request else None) + base_url = getattr(settings, 'WAGTAILAPI_BASE_URL', request.site.root_url if request and request.site else None) if base_url: # We only want the scheme and netloc