What's the best way to create a reusable pagination template?

62 views
Skip to first unread message

Frederik Creemers

unread,
Feb 27, 2017, 7:41:20 AM2/27/17
to Django users
The code for rendering pagination controls in my app is the same everywhere:

{% if is_paginated %}
   
<div class="row">
       
<div class="col xs-12">
           
{% if page_obj.has_previous %}
               
<a class="btn btn-primary" href="foo/?page={{ page_obj.previous_page_number }}">Previous</a>
            {%
endif %}
            {%
if page_obj.has_next %}
                <
a class="btn btn-primary"
                   href="foo/?page={{ page_obj.next_page_number }}">Previous</a>
            {%
endif %}
        </
div>
    </
div>
{%
endif %}

So I'm wondering whether there's a good w&ay to create the href for the previous and next buttons based on the current url. I can't just take the current url and append "?page=..." to it, since the url may already have a "page" parameter and/or other querystring parameters. On stackoverflow, I've seen people create a replace_url_parameter template tag, which replaces the given parameter by parsing the url, changing the param, and rebuilding the url again. I can do this, but this seems like such a common task that I'm surprised I can't find any tools to do this in django itself.

If there's an open source project that offers this, I might be interested, but I'm not sure if I want to take on an extra dependency just for pagination urls.

fabrixxm

unread,
Feb 28, 2017, 3:48:41 AM2/28/17
to Django users
Yep. My solution is a custom template tag

from django.template.defaulttags import register
from urllib.parse import urlencode

@register.simple_tag(takes_context=True)
def querystringmod(context, *args):
   
"""Modify current querystring:
     {% querystringmod name value [name value [...]] %}
    """

   
if (len(args) % 2) !=0:
        args
.append("")
    request
= context['request']
    current_qs
= request.GET.dict()
    current_qs
.update(dict([ (args[n], args[n+1]) for n in range(0, len(args), 2) ]))
   
return urlencode(current_qs)

in template
<a href="?{% querystringmod "page" page_obj.previous_page_number %}">previous</a>



Reply all
Reply to author
Forward
0 new messages