【问题标题】:Django Wagtail: get children of page using custom method in django regular viewDjango Wagtail:在 django 常规视图中使用自定义方法获取页面的子级
【发布时间】:2019-09-03 21:20:16
【问题描述】:

我正在玩 Wagtail 2.6.1,但遇到了令人困惑的问题。我需要在 vanilla Django 视图中使用 Page 模型。我想获得 BlogPage 的孩子,所以我制作了自定义方法,它应该返回所有子页面。方法有效,但仅在模板视图中。当我在 django 视图中访问它时,它返回空查询集。我真的不明白为什么。

我的models.py

class BlogPage(Page):
    template = "blog/blog.html"
    max_count = 1    
    subpage_types = ['blog.BlogPostPage','blog.PostAdvancedPage']        

    promote_panels = Page.promote_panels + [
       FieldPanel('menu_order'),
   ]

    def getChildren(self):
        children = self.get_children().live().all()        
        return children

    def get_context(self, request):
        context = super(BlogPage, self).get_context(request)
        context['categories'] = BlogCategory.objects.order_by('name').all() 
        context['blog_posts'] = self.get_children().live().order_by('-first_published_at').all()            
        return context

    class Meta:
        verbose_name = "Blog"
        verbose_name_plural = "Blogs"

我的意见.py

from .models import BlogPage

def post_filter(request):
    if request.method == 'POST':      

        posts = BlogPage().getChildren() # this return empty queryset
        print (posts)

但是当我在模板 blog.html 中呈现这个方法时它可以工作:

<div class="section py-9">
  {{self.getChildren}}
</div>

它成功渲染了模板中的所有子页面:

<PageQuerySet [<Page: Lorem Ipsum 01>,<Page: Lorem Ipsum 02>]>

请注意,我通常使用 get_context 方法来渲染模板中的所有帖子,我只是尝试在模板中渲染此方法 (getChildren) 以检查它是否有效。

【问题讨论】:

    标签: python django django-models wagtail


    【解决方案1】:

    BlogPage().getChildren() 行的意思是“在内存中创建一个新的BlogPage 实例,并获取它的孩子”。当然,由于它只是刚刚创建,它不会有任何子页面,因此返回一个空查询集。

    为了让post_filter 视图做一些有用的事情,您需要指定一个现有的BlogPage 实例,以便它调用getChildren。您还没有提到 post_filter 将如何使用,所以我不知道这些信息应该来自哪里 - 但一种可能性是将它作为 URL 中的参数传递,在这种情况下 post_filter 看起来像这样:

    def post_filter(request, page_id):
        if request.method == 'POST':
            posts = BlogPage.objects.get(id=page_id).getChildren()
            print (posts)
    

    【讨论】:

    • 您好 Gasman,非常感谢您,这是在 wagtail 项目中苦苦挣扎几天后的结果。我在这里犯了基本的python错误。你是对的,我正在创建新对象:(非常感谢你指出我正确的方向。
    猜你喜欢
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    相关资源
    最近更新 更多