Login

Pagination which preserves additional GET parameters

Author:
davegri
Posted:
July 15, 2015
Language:
Python
Version:
1.7
Tags:
pagination
Score:
0 (after 0 ratings)

Using this snippet you can easily create Pagination that preserves any additional GET paremters you may be using (for example for search module)

 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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
### views.py ###

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

# get any current GET parameters without the page modifier
       extra_param = request.GET.copy()
        if 'page' in  extra_param.keys():
            del  extra_param['page']

        length = len(object_list)

        # pagination
        paginator = Paginator(object_list , 1)

        # get page number from GET request
        page_num = request.GET.get('page', 1)

        # get objects from paginator according to page number
        try:
            objects = paginator.page(page_num)
        except(EmptyPage, InvalidPage):
            objects = paginator.page(paginator.num_pages)

        context_dict = {
            'object_amount': length,
            'objects': objects,
            'params' : extra_params,
        }

        return render(request, 'search.html', context_dict)


### Template ###

        <div class="pagination">
            <ul>
                {% if objects.has_previous %}
                    <li><a href="?{{params.urlencode}}&amp;page={{ objects.previous_page_number }}">previous</a></li>
                {% else %}
                    <li class="disabled">previous</li>
                {% endif %}
                {% for page in objects.paginator.page_range  %}
                    {% if page == summaries.number %}
                        <li><a class="active" href="?{{params.urlencode}}&amp;page={{ page }}" >{{ page }}</a></li>
                    {% else %}
                        <li><a href="?{{params.urlencode}}&amp;page={{ page }}" >{{ page }}</a></li>
                    {% endif %}
                {% endfor %}
                {% if objects.has_next %}
                    <li><a href="?{{params.urlencode}}&amp;page={{ objects.next_page_number }}">next</a></li>
                {% else %}
                    <li class="disabled">next</li>
                {% endif %}
            </ul>
        </div>

More like this

Comments

Please login first before commenting.