Django pagination and “current page”

后端 未结 3 798
旧时难觅i
旧时难觅i 2021-02-07 13:16

I\'m currently developing a Django application which will make use of the infamous \"pagination\" technique. I\'m trying to figure out how the django.core.paginator module work

3条回答
  •  北荒
    北荒 (楼主)
    2021-02-07 14:07

    django-pagination should do what you want and comes wrapped in a pretty package you can just plug-in and use. It essentially moves the code from your views to the templates and a middleware.

    EDIT: I just saw your edit. You can get the current objects on a page using {% autopaginate object_list %}, which replaces object_list with the current objects for any given page. You can iterate through it and if you want the first, you should be able to treat it like a list and do object_list[0].

    If you want to keep this within your views, you could do something like this:

    def show_question(question_pk):
        questions = Question.objects.all()
        paginator = Paginator(questions, 20)
        return render_to_response('show_question.html', { 'page' : paginator })
    

    Within your template, you can access the current page you're on by doing:

    # Gives you the starting index for that page.
    # For example, 5 objects, and you're on the second page. 
    # start_index will be 3.
    page.start_index
    
    # You can access the current page number with:
    # 1-based index
    page.number
    

    With that, you should be able to do everything you need. There are a couple good examples here.

提交回复
热议问题