更改页面在URL中的显示位置

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

我已经设置了我的网站,主要的父母/树结构是Home > Shop > Category > Product">表示父母的。

这工作正常,但是当访问Product(Page)时,网址会自动(并且正确地)在Waztail的/shop/test-category/test-product上配置。

我想改变它,以便产品实际显示为在根级别(即使它不是)。因此,如果用户访问测试产品,它将在/test-product/

通过文档查看,RoutablePageMixin似乎可以做到这一点,但我不知道如何实现它。有任何想法吗?

wagtail
1个回答
2
投票

此解决方案将使这两个URL上的产品可用:

  • /shop/test-category/test-product/
  • /test-product/

做法:

你是正确的,你将需要使用RoutablePageMixin,请确保按照导入前的说明将其安装在installed_apps中。

下面的示例将RoutablePageMixin添加到您的HomePage,因为这是位于根/ URL的页面。我们在尾随/之前进行正则表达式检查和匹配单个slug。

然后我们看看我们是否能找到一个带有那个slug的ProductPage,然后服务(或重定向)到那个页面。最后,如果没有匹配,我们使用当前请求调用home_page的serve方法来处理其他任何事情。这可能是不正确的URL或正确的子页面URL。

注意事项:

  • 如果你有一个与产品页面相同的子页面,子页面将永远不会加载,这个代码中没有聪明的东西可以解决这个问题。如果将来成为问题,您可以在产品名称和子页面名称的验证中加入一些逻辑。
  • 这不考虑搜索引擎优化问题,搜索引擎会将这些视为不同的页面,因此您可能需要考虑在元标记中声明您的canonical URL
  • 这不会从/shop/test-category/test-product/重定向到/test-product/ - 这可以通过覆盖你的serve上的ProductPage方法并重定向到home_page.url + '/' + self.slug之类的东西来完成。

示例代码:

# models.py - assuming all your models are in one file
from django.db import models
from django.shortcuts import redirect  # only needed if redirecting

from wagtail.admin.edit_handlers import FieldPanel
from wagtail.contrib.wagtailroutablepage.models import RoutablePageMixin, route
from wagtail.core.models import Page


class ProductPage(Page):
    price = models.DecimalField(max_digits=5, decimal_places=2)

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


class HomePage(RoutablePageMixin, Page):

    @route(r'^(?P<product_slug>[\w-]+)/$')
    def default_view(self, request, product_slug=None):
        """Route will match any `my-product-slug/` after homepage route."""
        product_page = Page.objects.exact_type(ProductPage).filter(slug=product_slug).first()
        if product_page:
            # option 1 - redirect to the product's normal URL (non-permanent redirect)
            # return redirect(product_page.specific.url)
            # option 2 - render the product page at this URL (no redirect)
            return product_page.specific.serve(request)
        else:
            # process to normal handling of request so correct sub-pages work
            return self.serve(request)
© www.soinside.com 2019 - 2024. All rights reserved.