【问题标题】:Wagtail render any path in index pageWagtail 在索引页面中呈现任何路径
【发布时间】:2018-10-01 23:45:31
【问题描述】:

我需要使某些页面能够编写不依赖于站点结构的任意 URL。

例如我有结构:

/
/blog
/blog/blogpost1
/blog/blogpost2

但是,例如,我需要将 url 从 /blog/blbogpost2 更改为 /some/blogpost/url1

为此,我决定给机会处理网站主页的任何 URL。

class IndexPage(RoutablePageMixin, Page):
    ...
    @route(r'^(?P<path>.*)/$')
    def render_page_with_special_path(self, request, path, *args, **kwargs):
        pages = Page.objects.not_exact_type(IndexPage).specific()
        for page in pages:
            if hasattr(page, 'full_path'):
                if page.full_path == path:
                    return page.serve(request)
        # some logic

但是现在,如果没有找到这个path,但我需要将此请求返回给标准处理程序。我该怎么做?

【问题讨论】:

    标签: python django wagtail


    【解决方案1】:

    RoutablePageMixin 无法做到这一点; Wagtail 将 URL 路由和页面服务视为两个不同的步骤,一旦确定了负责为页面提供服务的函数(对于RoutablePageMixin,这是通过检查@route 中给出的 URL 路由来完成的),就没有办法了回到 URL 路由步骤。

    但是可以通过overriding the page's route() method来完成,这是低级机制used by RoutablePageMixin。你的版本应该是这样的:

    from wagtail.core.url_routing import RouteResult
    
    class IndexPage(Page):
        def route(self, request, path_components):
            # reconstruct the original URL path from the list of path components
            path = '/'
            if path_components:
                path += '/'.join(path_components) + '/'
    
            pages = Page.objects.not_exact_type(IndexPage).specific()
            for page in pages:
                if hasattr(page, 'full_path'):
                    if page.full_path == path:
                        return RouteResult(page)
    
            # no match found, so revert to the default routing mechanism
            return super().route(request, path_components)
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 2021-11-14
    • 1970-01-01
    • 2022-12-20
    • 1970-01-01
    • 2023-01-14
    • 2017-03-12
    • 2012-08-31
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多