我在这里有一个Wagtail项目的HomePage
模型片段,该项目充当我的博客索引页面。由于在我向其中添加Django的分页逻辑时,get_context()
有点冗长,因此我决定尝试将其放入自己的方法中,而只是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页都会被投放。我快速而又肮脏的解决方案是仅在request
中将pagination()
作为自变量添加,然后在request
中将get_context()
传递给它。这解决了问题,但我不禁认为此解决方案存在问题,或者某种程度上不是最佳实践。谁能告诉我解决这个问题的更好方法,和/或不经修改就将变量从一个函数传递到另一个函数是否是个坏主意?还是真的好吗?
这是我的代码现在的外观,一切似乎都正常运行:
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(request, 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, request, posts):
paginator = Paginator(posts, 5)
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
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
非常感谢大家!