DEV Community

Adam Mateusz Brożyński
Adam Mateusz Brożyński

Posted on

Wagtail page explorer: redirect to edit if subpages not allowed

When clicking on a page in explorer, it shows a list of its subpages by default. This also applies to page models with subpage_types = []. This is confusing, and it's better to redirect the user to the edit page instead of showing him an empty list of subpages.

To achieve this, we need to create middleware.py and add it to MIDDLEWARE in base.py (for ex. "pages.middleware.RedirectToEditMiddleware" if we have our file in /pages/middleware.py).

Here is a code that allows us to fix this issue:

from django.http import HttpResponseRedirect
from django.urls import reverse
from wagtail.models import Page

class RedirectToEditMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        if '/admin/pages/' in request.path:
            page_id = request.resolver_match.kwargs.get('parent_page_id')
            if page_id is not None:
                page = Page.objects.get(id=page_id)
                if not page.specific.allowed_subpage_models():
                    return HttpResponseRedirect(reverse('wagtailadmin_pages:edit', args=(page_id,)))

        return response
Enter fullscreen mode Exit fullscreen mode


`

Top comments (0)