【发布时间】: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