Wagtail:在基于类的视图中以编程方式呈现页面

时间:2018-03-04 21:00:52

标签: python django django-models django-class-based-views wagtail

我有一个Wagtail设置,用户可以选择要渲染的页面,如果没有设置,它会使用ListView最近的帖子返回一个列表页面。这是设置:

@register_setting
class PeregrineSettings(BaseSetting):
    """
    Settings for the user to customize their Peregrine blog.
    """
    landing_page = models.ForeignKey(
        'wagtailcore.Page',
        null=True,
        blank=True,
        on_delete=models.SET_NULL,
        help_text='The page to display at the root. If blank, displays the latest posts.'
    )

设置有效。当我尝试在ListView中使用它时,我试图将url_path传递给Wagtail的serve方法,但它不会呈现页面视图;我得到了404.这是ListView的代码:

class PostsListView(ListView):
    """
    Paginated view of blog posts.
    """
    model = SitePost
    template_name = 'peregrine/site_post_list.html'
    context_object_name = 'posts'
    paginate_by = 10
    ordering = ['-post_date']

    def get(self, request, *args, **kwargs):
        peregrine_settings = PeregrineSettings.for_site(request.site)
        if peregrine_settings.landing_page is None:
            # Render list of recent posts
            response = super().get(request, *args, **kwargs)
            return response
        else:
            # Render landing page
            return serve(request, peregrine_settings.landing_page.url_path)

感觉我错过了将Page中存储的peregrine_settings.landing_page实例传递给要渲染的方法的方法。任何人都可以对这里的工作内部有所了解吗?谢谢!

1 个答案:

答案 0 :(得分:2)

我认为你在这里调用的serve函数是wagtail.core.views中定义的视图吗?这个视图本身并没有太大作用 - 它在站点根页面上调用route()来找到正确的页面,然后调用该页面的serve()方法(传递请求对象)来进行实际的页面渲染。看起来后面的serve()方法就是你所需要的:

def get(self, request, *args, **kwargs):
    peregrine_settings = PeregrineSettings.for_site(request.site)
    if peregrine_settings.landing_page is None:
        # ...
    else:
        # Render landing page
        return peregrine_settings.landing_page.serve(request)

有关routeserve方法的更多文档可在此处找到: http://docs.wagtail.io/en/v2.0/reference/pages/theory.html#anatomy-of-a-wagtail-request http://docs.wagtail.io/en/v2.0/reference/pages/model_recipes.html#overriding-the-serve-method