Simple Paginator Function

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def get_paginators(request, objects, per_page=20, paginator_range=5):
    paginator_range = int(paginator_range)
    from django.core.paginator import Paginator, InvalidPage, EmptyPage
    paginator = Paginator(objects, per_page)

    # Make sure page request is an int. If not, deliver first page.
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1

    # If page request (9999) is out of range, deliver last page of results.
    try:
        obj_list = paginator.page(page)
    except (EmptyPage, InvalidPage):
        obj_list = paginator.page(paginator.num_pages)

    if obj_list.number-paginator_range >= 0:
        from_ = obj_list.number-paginator_range
    else:
        from_ = 0

    if obj_list.number+paginator_range <= len(paginator.page_range):
        to_ = obj_list.number+paginator_range
    else:
        to_ = len(paginator.page_range)

    page_range = paginator.page_range[from_:to_]

    return (obj_list, page_range)

# Use follwing code in your template to show page_range
{% for item in page_range %}
  {% ifequal item event_list.number %}
    <span class="current number">{{item}}</span>
  {% else %}
    <a href="?page={{item}}" class="number">{{item}}</a>
  {% endifequal %}
{% endfor %}

More like this

  1. Pagination/Filtering Alphabetically by zain 5 years, 1 month ago
  2. Pagination shortcut by piratus 5 years, 1 month ago
  3. Admin: return to change_list with filter and pagination applied by fx 3 years ago
  4. Extended Paginator by davisp 6 years, 8 months ago
  5. Accessing URL variable from within a Form by blacktav 7 months, 3 weeks ago

Comments

(Forgotten your password?)