【问题标题】:Is there a way to hide part of a URL created from the Wagtail admin page tree?有没有办法隐藏从 Wagtail 管理页面树创建的部分 URL?
【发布时间】:2019-05-11 05:53:22
【问题描述】:

假设我为我的网站创建了一个博客。 Wagtail 管理中的树结构设置如下所示:

首页 > 博客索引 > 博客文章

是否可以将博客索引页面保留在管理页面树中,但将其从 URL 中删除,以便我的 URL 看起来像这样:

主页 > 博客文章

我正在为博客索引页面分配一个自定义组,允许他们仅编辑他们创建的博客文章,这就是博客索引需要保留在管理端树中的原因。

我对 routablepagemixin 做了一些工作,但不是要从 URL 中删除任何内容,只是添加它。

【问题讨论】:

    标签: django wagtail


    【解决方案1】:

    我不完全确定 RoutablePageMixin 是否是解决此问题的正确方法,但这就是我之前解决此问题的方法。

    这是一个示例,说明如何使用 RoutablePageMixinroute 进行操作(注意:我很快就将其拼凑在一起并没有对其进行测试,您可能需要进行一些调整)

    from django.http import HttpResponseRedirect
    
    from wagtail.contrib.routable_page.models import RoutablePageMixin, route
    from wagtail.core.models import Page
    
    from blog.models import BlogPage
    
    
    class HomePage(RoutablePageMixin, Page):
        """A home page class."""
    
        # HomePage Fields here...
    
        # This route will collect the blog slug
        # We'll look for the live BlogPost page.
        @route(r"^(?P<blog_slug>[-\w]*)/$", name="blog_post")
        def blog_post(self, request, blog_slug, *args, **kwargs):
            try:
                # Get the blog page
                blog_page = BlogPage.objects.live().get(slug=blog_slug)
            except BlogPage.DoesNotExist:
                # 404 or post is not live yet
                return HttpResponseRedirect("/")
            except Exception:
                # Handle your other exceptions here; here's a simple redirect back to home
                return HttpResponseRedirect("/")
    
            # Additional logic if you need to perform something before serving the blog post
    
            # Let the blog post page handle the serve
            return blog_page.specific.serve(request, *args, **kwargs)
    

    还有一点需要注意:您需要更改原始博客文章页面上的站点地图 URL,这样它们就不会在 sitemap.xml 中显示为 /blog/blog-slug/

    【讨论】:

    • 谢谢@Kalob,它的工作原理和发布的差不多。我遇到的唯一问题是 HttpResponseRedirect 需要高于所有其他问题。起初并没有意识到这一点。然而,我最终改变了主意,因为即使这有效,旧 URL 仍然可用,无论是访问它的目录还是从 Wagtail 管理员中访问。这最终会让用户感到困惑。相反,我会找到一种方法来使用博客索引页面来获取一些有用的内容。另外,非常感谢您在https://learnwagtail.com 提供的视频教程。他们帮了大忙!
    • 您也可以覆盖原始页面模型上的serve() 方法以重定向到此可路由页面。这最终成为我发现的很多工作。另一种选择是将您的博客文章放在主页下,并在您拥有大量页面后利用 wagtails 页面搜索。很高兴您发现这些视频很有帮助!! :)
    • 我也想做同样的事情,但我决定不做,因为感觉太老套了。我认为能够在管理员的不同文件夹中组织您的内容,同时让他们可以灵活地拥有自己的 URL 模式,这将是一个很棒的功能。
    猜你喜欢
    • 1970-01-01
    • 2020-06-24
    • 2019-12-26
    • 2019-02-19
    • 2020-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-26
    相关资源
    最近更新 更多