Prefixed Parameters for Django querystring tag

An overview of Django 5.1's new querystring tag and how to add support for prefixed parameters.

Posted on Feb. 13, 2025 in django.

New in Django 5.1, the querystring template tag enables, among other things, updating the query string.

This is useful when a URL already contains parameters, and you just want to set or update one or a few parameters while keeping all others.

For example, a link to the next page from the Django documentation:

{% querystring page=page.next_page_number %}

But what if there are two paginations on the same page? In such cases, it's common to prefix the page parameter, but querystring does not support prefixing.

Fortunately, it's easy to create a custom template tag on top of querystring that supports prefixing:

from django import template
from django.template.defaulttags import querystring


register = template.Library()


@register.simple_tag(takes_context=True)
def querystring_with_prefix(context, prefix, query_dict=None, **kwargs):
    """Extend django querystring with a prefix for given parameters.

    Usage example::

        {% querystring "prefix_" page=page_obj.next_page_number %}
    """
    new_kwargs = {f"{prefix}{key}": value for key, value in kwargs.items()}
    return querystring(context, query_dict, **new_kwargs)

With this simple tweak, you can handle prefixed query parameters effortlessly.

Got a better approach? Let’s discuss! Follow me on Bluesky: @bmihelac.bsky.social

Share on Reddit