Pagination and get parameters

The generic solution is to define a "custom template tag" (a function) which keeps the complete URL but updates the GET parameters you pass to it.

After registration, you can use this function in your templates:

<a href="?{% query_transform page=contacts.previous_page_number %}">previous</a>

To define and register the custom template tag, include this code in a python file:

from django import template

register = template.Library()

@register.simple_tag(takes_context=True)
def query_transform(context, **kwargs):
    query = context['request'].GET.copy()
    for k, v in kwargs.items():
        query[k] = v
    return query.urlencode()

*Thanks to Ben for the query_transform code. This is an adapation for python 3 from his code.

Why this method is better than reconstructing the URLs manually:

If you later decide that you need additional parameters in your URLs: 1. you don't have to update all the links in your templates. 2. You don't need to pass all the params required for recostructing the URL to the templates.


Typically, to preserve GET parameters you simply re-write them manually. There shouldn't be many cases where having to do this will matter.

&page={{page}}&total={{total}}

You can abstract this away into a template include or a custom template tag.

https://docs.djangoproject.com/en/1.11/howto/custom-template-tags/

Additionally, you could create a string filter that takes URL params as a string as well as a dict of values you want to change. The filter could then parse the params string, update the value, then recombine the string back into URL params.

{{ request.get_full_path | update_param:'page=8' }}

Tags:

Django