【问题标题】:How can I get a "flatter" URL in Wagtail?如何在 Wagtail 中获得“更扁平”的 URL?
【发布时间】:2019-09-06 19:39:25
【问题描述】:

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

可以通过如下 URL 访问它们:

  • /destinations/伦敦
  • /destinations/伯明翰
  • /destinations/manchester

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

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

这是为了让 Wagtail 管理员井井有条,同时也防止 URL 深度嵌套。

【问题讨论】:

    标签: django wagtail


    【解决方案1】:

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

    HomePage --> Destination Index --> Destinations
    

    HomePage 会有这个 mixin:

    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 会有这个 mixin:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-31
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 1970-01-01
      • 1970-01-01
      • 2019-12-13
      • 1970-01-01
      相关资源
      最近更新 更多