如何在Wagtail中获得“更平坦”的URL?

问题描述 投票:1回答:1

我有一个直接位于根页面内的DestinationIndexPage模型,其中有多个DestinationPage实例。

可以使用以下URL访问它们:

  • /目的地/伦敦
  • /目的地/伯明翰
  • /目的地/曼彻斯特

有没有办法将目标页面保留在DestinationIndexPage中,但是从以下URL提供它们?

  • /伦敦
  • /伯明翰
  • /曼彻斯特

这是为了保持Wagtail管理员的有序,但也防止深层嵌套的URL。

django wagtail
1个回答
0
投票

因为我只会隐藏一个孩子page,所以我创建了一些mixin来“隐藏”一个页面。采用以下层次结构:

HomePage --> Destination Index --> Destinations

HomePage会有这个混合:

class ConcealedChildMixin(Page):
    """
    A mixin to provide functionality for a child page to conceal it's
    own URL, e.g. `/birmingham` instead of `/destination/birmingham`.
    """

    concealed_child = models.ForeignKey(
        Page,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='concealed_parent',
        help_text="Allow one child the ability to conceal it's own URL.",
    )

    content_panels = Page.content_panels + [
        FieldPanel('concealed_child')
    ]

    class Meta:
        abstract = True

    def route(self, request, path_components):
        try:
            return super().route(request, path_components)
        except Http404:
            if path_components:
                subpage = self.specific.concealed_child

                if subpage and subpage.live:
                    return subpage.specific.route(
                        request, path_components
                    )

            raise Http404

Destinations将有这个混合:

class ConcealedURLMixin:
    """
    A mixin to provide functionality for a page to generate the correct
    URLs if it's parent is concealed.
    """

    def set_url_path(self, parent):
        """
        Overridden to remove the concealed page from the URL.
        """
        if parent.concealed_parent.exists():
            self.url_path = (
                '/'.join(
                    [parent.url_path[: len(parent.slug) - 2], self.slug]
                )
                + '/'
            )
        else:
            self.url_path = super().set_url_path(parent)

        return self.url_path
© www.soinside.com 2019 - 2024. All rights reserved.