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 | from django import template
register = template.Library()
def paginator(context, adjacent_pages=2):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
page_numbers = [n for n in \
range(context['page'] - adjacent_pages, context['page'] + adjacent_pages + 1) \
if n > 0 and n <= context['pages']]
return {
'hits': context['hits'],
'results_per_page': context['results_per_page'],
'page': context['page'],
'pages': context['pages'],
'page_numbers': page_numbers,
'next': context['next'],
'previous': context['previous'],
'has_next': context['has_next'],
'has_previous': context['has_previous'],
'show_first': 1 not in page_numbers,
'show_last': context['pages'] not in page_numbers,
}
register.inclusion_tag('paginator.html', takes_context=True)(paginator)
|
Comments
VERY COOL! This saved me a bunch of work. I did make a minor change (just a style difference really):
page_numbers = range(max(0, context['page']-adjacent_pages), min(context['pages'], context['page']+adjacent_pages)+1)
#
(This is my first python contribution. I hope it is correct and useful. Please email me at [myFirstName]@[myLastName].com with any corrections.)
I've patched this to add:
results_this_page- On the last page, there will usually be less than results_per_page results to displayfirst_this_page- the starting point of the slice that object_list representslast_this_page- the ending point of the slice that object_list representsAs a result, I can use the following paginator.html template:
To get these results on the pages:
I'd also like to throw out a NOTICE that in order to implement this snippet, you must follow http://www.djangoproject.com/documentation/templates_python/#extending-the-template-system As a new user to both Python and Django, I was trying to out this in my views.py, which does not work. I hope that saves someone from wasting the time I did.
BEGIN PATCH
#
Oh yea, in that patch I also changed it to use a decorator. I don't know much about python, but I think that is appropriate.
#
I think this is a very important improvement. I hate having to keep adding to the context list as my app matured. I should only have to add new context to my views. So, I came up with this.
To pass the entire context with modifications/additions to the template of an inclusion tag, you can use:
#
Could you please post a "view" example for this snippet?
#
Example of a view
View parameters and paginator.html?
How this template could be design in order to paginate any resource?
For instance, if you want to paginate instance of News model, then instance of Category model and so forth, links in paginator must be dynamics. Till now I can't figure out how to do this neat and clean.
So, how transmit those parameters to the template?
#