我这里有一个来自Wagtail项目中的HomePage
模型的片段,它充当了我的博客索引页。由于get_context()
在添加Django的分页逻辑时变得有点冗长,所以我决定尝试将其放入自己的方法中,并让get_context()
从中获取Page
对象的分页集合。下面是我的代码最初的样子:
class HomePage(RoutablePageMixin, Page):
description = models.CharField(max_length=255, blank=True, null=True)
content_panels = Page.content_panels + [
FieldPanel('description', classname='full')
]
def get_context(self, request, *args, **kwargs):
context = super(HomePage, self).get_context(request, *args, **kwargs)
context['posts'], context['page_range'] = self.pagination(self.get_posts())
# End attempt
context['home_page'] = self
context['search_type'] = getattr(self, 'search_type', '')
context['search_term'] = getattr(self, 'search_term', '')
return context
def get_posts(self):
return BlogPage.objects.descendant_of(self).live().order_by('-date')
def pagination(self, posts):
paginator = Paginator(posts, 5)
try:
page = request.GET.get('page', '1')
except:
page = 1
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
# Get a page_range
index = posts.number - 1
max_index = len(paginator.page_range)
start_index = index - 5 if index >= 5 else 0
end_index = index + 5 if index <= max_index - 5 else max_index
page_range = paginator.page_range[start_index:end_index]
print('\n', posts, '\n')
return posts, page_range
我没有立即发现问题,但当然注意到无论URL中的page
参数是什么,页面1都在被服务。我快速而肮脏的解决方案是在pagination()
中添加request
作为参数,然后在get_context()
中向上传递{
下面是我的代码现在的样子,一切似乎都正常工作:
^{pr2}$提前感谢大家!在
目前没有回答
相关问题 更多 >
编程相关推荐