How to do paginator without request?

Question:



def page_look(post_list, request):

    paginator = Paginator(post_list, settings.VIEW_COUNT)

    page_number = request.GET.get('page')

    page_obj = paginator.get_page(page_number)

    return page_obj 

This is a social media site with posts. Paginator working good, but rewiever said me to do it without request. I need to make it as a helper function wiyh ten posts per page.

Reviewer tells me to work with page_number, but im not smart enought to solve this, pls help

Asked By: SeritoTheMaid

||

Answers:

Based on your description, I think they just want the page_look function to take a page number directly, as in:

def page_look(post_list, page_number):
    paginator = Paginator(post_list, settings.VIEW_COUNT)
    page_obj = paginator.get_page(page_number)
    return page_obj 

Then the CALLER deals with the request.

    page_number = request.GET.get('page')
    page_obj = page_look(post_list, page_number)

This is a sensible change, because now you can call page_look for a given page without having to have a request first.

Answered By: Tim Roberts

I think what they mean is that you should pass the page, not the request, so:

from django.conf import settings


def page_look(post_list, page_number):
    paginator = Paginator(post_list, getattr(settings, 'VIEW_COUNT', 20))
    page_obj = paginator.get_page(page_number)
    return page_obj

and thus pass the request.GET.get('page') to the function instead.

You can further generalize this, which is basically what a MultipleObjectMixin does:

def paginate_queryset(queryset, page=None, page_size=None):
    paginator = Paginator(
        queryset, page_size, page_size or getattr(settings, 'VIEW_COUNT', 20)
    )
    page = page or 1
    try:
        page_number = int(page)
    except ValueError:
        if page == 'last':
            page_number = paginator.num_pages
        else:
            raise
    return paginator.get_page(page_number)

this also allows us to pass the page_size optionally, and will select the last page if the page is 'last', or 1 if no page was given.

That being said, often if you need pagination, using class-based views, like a ListView [Django-doc] are easier.

Answered By: Willem Van Onsem
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.