我已经设置了我的网站,主要的父母/树结构是Home > Shop > Category > Product"
,>
表示父母的。
这工作正常,但是当访问Product(Page)
时,网址会自动(并且正确地)在Waztail的/shop/test-category/test-product
上配置。
我想改变它,以便产品实际显示为在根级别(即使它不是)。因此,如果用户访问测试产品,它将在/test-product/
。
通过文档查看,RoutablePageMixin
似乎可以做到这一点,但我不知道如何实现它。有任何想法吗?
此解决方案将使这两个URL上的产品可用:
/shop/test-category/test-product/
/test-product/
做法:
你是正确的,你将需要使用RoutablePageMixin
,请确保按照导入前的说明将其安装在installed_apps中。
下面的示例将RoutablePageMixin
添加到您的HomePage
,因为这是位于根/
URL的页面。我们在尾随/
之前进行正则表达式检查和匹配单个slug。
然后我们看看我们是否能找到一个带有那个slug的ProductPage
,然后服务(或重定向)到那个页面。最后,如果没有匹配,我们使用当前请求调用home_page的serve
方法来处理其他任何事情。这可能是不正确的URL或正确的子页面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)