在视图中获取当前页面分页并手动设置页面数

时间:2015-03-31 08:37:24

标签: python django pagination

  1. 我需要在view.py
  2. 中手动设置分页的页数
  3. 我需要获取当前页面的数量以便在功能中处理它。 我接下来view.py:

    class VideoListView(ListView):
        template_name = "video/list.html"
        context_object_name = 'videos'
        paginate_by = 12
        request = requests.get(settings.YOUTUBE_VIDEO_COUNT_URL)
        count = simplejson.loads(request.text)['data']['totalItems']
    
        def get_queryset(self, **kwargs):
            request = requests.get(settings.YOUTUBE_VIDEO_URL)
            data_about = simplejson.loads(request.text)
            video_list = []
            for item in data_about['data']['items']:
                video_list.append(item)
            return video_list
    
  4. 页数必须是:count / paginate_by,并且在每个页面上请求json都不同。

1 个答案:

答案 0 :(得分:3)

Django分页是通过 GET 存储的,所以在你的 ListView 中你需要访问:

# This will assume, if no page selected, it is on the first page
actual_page = request.GET.get('page', 1)
if actual_page:
    print actual_page

因此,在列表视图代码中,取决于您需要它的位置,但如果您在 get_queryset 函数中需要它,则可以使用访问请求

class VideoListView(ListView):
    # ..... your fields

    def get_queryset(self, **kwargs):
        # ... Your code ...
        actual_page = self.request.GET.get('page', 1)
        if actual_page:
            print actual_page
        # ... Your code ...

使用Django Pagination的自定义分页对象:

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger

def CreatePagination(request, obj_list):
    # Create the pagination
    RESULTS_PER_PAGE = 10
    paginator = Paginator(obj_list, RESULTS_PER_PAGE)
    page = request.GET.get('page')  # Actual page
    try:
        page_list = paginator.page(page)
    except PageNotAnInteger:
        # If page is not an integer, deliver first page.
        page_list = paginator.page(1)
    except EmptyPage:
        # If page is out of range (e.g. 9999), deliver last page of results.
        page_list = paginator.page(paginator.num_pages)

    return page_list

要使用此CreatePagination函数,您需要将请求和对象列表传递给它。该请求用于获取实际页面,对象列表用于生成分页。

此功能将返回您可以在模板中管理的分页,就像您从ListView

管理自动生成的分页一样