Search code examples
djangodjango-pagination

Django - Pagination in Django 1.3


I'm new to Django. I'm using the simple pagination that Django provides but I need to paginate pages like this:

Prev 1 2 3 4 5 6 ... 320

Or

Prev 120 121 122 123 Last

There are some code ready to reuse in Django 1.3 to achieve this?


Solution

  • Let's supose we have a view:

    dev showPage(request,pg):
    

    where pg is the page number you are looking at this moment. Then we need a bit of code to get queryset (or objects) and create paginator object:

    pg = int(pg)
    objects = range(320)
    p = Paginator(objects, 15)
    page = p.page(pg)
    

    Well, that you need to get:

    Prev 1 2 3 4 5 6 ... 320
    

    is send to template a list like pags:

    pags = []   #var to be sent to template
    if pg-1 in p.page_range: pags.append( ( 'Prev', p.page( pg - 1) , ) )
    for n in range( pg-2, pg+2):
       if n in p.page_range: pags.append( ( n, p.page( pg - 2) , ) )
    if p.end_index() not in range( pg-2, pg+2):
       pags.append( ( '...', None , ) )
       pags.append( ( p.end_index(), p.end_index(), ) )
    

    now send pags to your template. And render to something like:

    <ul>
    {% for label, npag in pags %}
       <li>
       {%if npag %} <a href="asjflasdjf/{{npag}"}>{%endif%}
       label
       {%if npag %} </a> {%endif%}
       </li>
    {% endfor %}
    </ul>
    

    for

    Prev 120 121 122 123 124 Last
    

    the solution is the same. Decorate a little with css and you get it.

    Also, for example, you can assign a class for current page in order to get it in bold style:

    {%if npag %} 
       <a href="asjflasdjf/{{npag}"    
          {% if npag == pg %} class="bold-style" {%endif%}
       }>
    {%endif%}