Pagination example

In this example we will create a paginator using the django.core.paginator.



ajax.py

from dajaxwebsite.examples.views import get_pagination_page
from django.template.loader import render_to_string
from dajaxice.decorators import dajaxice_register

@dajaxice_register
def pagination(request, p):

    items = get_pagination_page(p)
    render = render_to_string('examples/dajax/pagination_page.html', {'items': items})

    dajax = Dajax()
    dajax.assign('#pagination', 'innerHTML', render)
    return dajax.json()

views.py

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

def get_pagination_page(page=1):
    items = range(0, 100)
    paginator = Paginator(items, 10)
    try:
        page = int(page)
    except ValueError:
        page = 1

    try:
        items = paginator.page(page)
    except (EmptyPage, InvalidPage):
        items = paginator.page(paginator.num_pages)

    return items

html

{% for i in items.object_list %}
    {{ i }}<br>
{% endfor %}

<div class="pagination">
    <span class="step-links">
        {% if items.has_previous %}
            <a href="#" onclick="Dajaxice.examples.pagination(Dajax.process,{'p':{{ items.previous_page_number }}})">previous</a>
        {% endif %}

        <span class="current">
            Page {{ items.number }} of {{ items.paginator.num_pages }}.
        </span>

        {% if items.has_next %}
            <a href="#" onclick="Dajaxice.examples.pagination(Dajax.process,{'p':{{ items.next_page_number }}})">next</a>
        {% endif %}
    </span>
</div>