如何在基于类的视图中获取分页器信息?我想从get_context_data中调用一个函数,我需要传递当前页面和最后一页。
views.py:
function abcWords(str as string) as long
dim i as long, arr as variant
arr = split(str, chr(32))
for i=lbound(arr) to ubound(arr)
abcWords = abcWords - int(not isnumeric(arr(i)))
next i
end function
答案 0 :(得分:2)
此代码片段摘自Django源代码views/generic/list.py
:
def get_context_data(self, *, object_list=None, **kwargs):
"""Get the context for this view."""
queryset = object_list if object_list is not None else self.object_list
page_size = self.get_paginate_by(queryset)
context_object_name = self.get_context_object_name(queryset)
if page_size:
paginator, page, queryset, is_paginated = self.paginate_queryset(queryset, page_size)
context = {
'paginator': paginator, #<--- (1)
'page_obj': page, #<--- (2)
'is_paginated': is_paginated,
'object_list': queryset
}
else:
context = {
....
}
if context_object_name is not None:
context[context_object_name] = queryset
context.update(kwargs)
return super().get_context_data(**context)
这意味着您的context
中的page_obj和paginator可用。您可以将表达式编写为:
{{ page_obj.previous_page_number }} (2)
或
{{ paginator.num_pages }} (1)
您还可以编写:
def get_context_date(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
my_function( )
context['page-list'] = pageList(context['page_obj'].number,
context['paginator'].num_pages)
return context