Use get_base_queryset in related pages fields

Eg, children, descendants and parent

This fixes a very minor bug in the admin API where the "parent" field
wasn't being populated if it that page was outside of the default site.
This commit is contained in:
Karl Hobley 2019-11-05 12:59:23 +00:00 committed by Karl Hobley
parent a2b97737eb
commit 673864d28b
5 changed files with 20 additions and 11 deletions

View file

@ -51,7 +51,7 @@ class PageChildrenField(Field):
def to_representation(self, page):
return OrderedDict([
('count', page.numchild),
('count', self.context['base_queryset'].child_of(page).count()),
('listing_url', get_model_listing_url(self.context, Page) + '?child_of=' + str(page.id)),
])
@ -71,7 +71,7 @@ class PageDescendantsField(Field):
def to_representation(self, page):
return OrderedDict([
('count', page.get_descendants().count()),
('count', self.context['base_queryset'].descendant_of(page).count()),
('listing_url', get_model_listing_url(self.context, Page) + '?descendant_of=' + str(page.id)),
])

View file

@ -518,6 +518,14 @@ class TestAdminPageDetail(AdminAPITestCase, TestPageDetail):
self.assertEqual(content['__types']['demosite.BlogIndexPage']['verbose_name'], 'blog index page')
self.assertEqual(content['__types']['demosite.BlogIndexPage']['verbose_name_plural'], 'blog index pages')
# Overriden from public API tests
def test_meta_parent_id_doesnt_show_root_page(self):
# Root page is visible in the admin API
response = self.get_response(2)
content = json.loads(response.content.decode('UTF-8'))
self.assertIsNotNone(content['meta']['parent'])
def test_field_ordering(self):
# Need to override this as the admin API has a __types field

View file

@ -464,3 +464,11 @@ class PagesAPIViewSet(BaseAPIViewSet):
return page
return super().find_object(queryset, request)
def get_serializer_context(self):
"""
The serialization context differs between listing and detail views.
"""
context = super().get_serializer_context()
context['base_queryset'] = self.get_base_queryset()
return context

View file

@ -8,7 +8,7 @@ from taggit.managers import _TaggableManager
from wagtail.core import fields as wagtailcore_fields
from .utils import get_object_detail_url, pages_for_site
from .utils import get_object_detail_url
class TypeField(Field):
@ -121,8 +121,7 @@ class PageParentField(relations.RelatedField):
def get_attribute(self, instance):
parent = instance.get_parent()
site_pages = pages_for_site(self.context['request'].site)
if site_pages.filter(id=parent.id).exists():
if self.context['base_queryset'].filter(id=parent.id).exists():
return parent
def to_representation(self, value):

View file

@ -32,12 +32,6 @@ def get_object_detail_url(router, request, model, pk):
return get_full_url(request, url_path)
def pages_for_site(site):
pages = Page.objects.public().live()
pages = pages.descendant_of(site.root_page, inclusive=True)
return pages
def page_models_from_string(string):
page_models = []