Login

django paginator

Author:
mhangman
Posted:
November 19, 2009
Language:
Python
Version:
1.1
Score:
1 (after 1 ratings)

This a basic pagination example. It shows new 5 pnews items. We added a code to our template so we can view previous or next pages. It also show us how many pages we have.

 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
#add this to views.py

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

def index(request, page=1):
 list = pnews.objects.all().order_by('-pdate')
 paginator = Paginator(list, 5)
 
 try:
  results = paginator.page(page)
 except(InvalidPage, EmptyPage):
  results = paginator.page(paginator.num_pages)
  
 return render_to_response('news/homepage.html', {"results":results})

#this to urls.py modify that for your urls
url(r'^news/(?P\d+)/$', 'cms.news.views.index', name='gmsnews'),

#this to your template so you can visit other pages
<div class="paginator-bottom">
    {%if results.has_previous%}
    <a href="{%url gmsnews results.previous_page_number%}">previous</a>
    {%endif%}
    <p>Page {{results.number}} of {{results.paginator.num_pages}}</p>
    {%if results.has_next%}
    <a href="{%url gmsnews results.next_page_number%}">next</a>
    {%endif%}
</div>

#note that you have to call pages like this
{% for pnews in results.object_list %}
#not like
{% for pnews in results %}

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

mhangman (on November 19, 2009):

i just dont want to add more app. to my project. this few code enaugh for me.

#

nsmgr8 (on November 19, 2009):

Just use object_list generic view.

#

Gauravwagh11 (on August 5, 2014):

I am getting error

TemplateSyntaxError: Could not parse the remainder: ' book_get books.previous_pa ge_number' from 'url book_get books.previous_page_number' at this line next

#

Please login first before commenting.