Wagtail Admin: how to sort the page tree

Jan. 27, 2023 · 2 min read

wagtail_image

In the sidebar of the administration panel of the Wagtail bar we can find the pages and browser on the tree of our website.

Navigation is simple and comfortable for the user until the moment the number of pages begins to grow and the horizontal scroll appears. Although only the title of the pages appears in the tree, they are not arranged alphabetically, which can make it difficult to find a specific page.

It is for this reason that we have received several requests to order the pages, to facilitate the work of content editors.

Although the documentation does not indicate how to do this, since we are working with a Django-based framework, we have been able to find out how to modify this behavior. To navigate through the page tree, Wagtail makes use of its internal page API, as can be seen in the image below:

From this URL, we were able to reach the sight PagesAdminAPIViewset and analyse behavior.

Taking advantage of Django's versatility, we can override the view to apply the desired sort order and capture the URL to redirect the http request from the CMS to our view.

If we want the pages in the tree to be ordered by their title, our new view should look something like this:

# views.py class CustomPagesAdminAPIViewSet(PagesAdminAPIViewSet): def get_queryset(self): qs = super().get_queryset() return qs.order_by("title")

and we will have to add a new router in our URLs before the Wagtail URLs. For the example, a project has been used where the Wagtail URLs are grouped into cms/, so each one would have to adjust the URLs to their project.

# urls.py admin_api = WagtailAPIRouter("custom_wagtailadmin_api") admin_api.register_endpoint("pages", CustomPagesAdminAPIViewSet) urlpatterns += [ path("cms/api/main/", admin_api.urls), ]

Once these changes have been applied, we can see in the CMS administrator how the pages in the tree appear ordered.

Comparte este artículo
Tags
Related posts