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

时间:2019-04-16 16:20:20

标签: django wagtail

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

可以使用如下网址访问它们:

  • / destinations / london
  • /目的地/伯明翰
  • /目的地/曼彻斯特

是否可以将目标页面保留在DestinationIndexPage内,但可以通过以下URL提供目标页面?

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

这是为了使Wagtail管理员井井有条,而且还可以防止嵌套的URL太深。

1 个答案:

答案 0 :(得分: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