querystring Tag

Utility Most Useful

Argument(s): mappings, key=value pairs

Documentation

Outputs a URL-encoded query string based on the provided parameters. The result always includes a leading ?, making it suitable for direct use in URLs.

New in Django 5.1.

Arguments

  • Positional arguments – Mappings like QueryDict or dict instances.
  • Keyword arguments – Key-value pairs to add or modify parameters.

If no positional arguments are provided, request.GET is used as the default source.

Basic Usage

Add or replace parameters in the current query string:

Template

<a href="{% querystring color='red' size='S' %}">Red, Small</a>

Result

<a href="?color=red&size=S">Red, Small</a>

Modifying the Current Query String

When used without positional arguments, it modifies the current request.GET:

Template

{# If current URL is ?color=blue&size=M #}
<a href="{% querystring size='L' %}">Large</a>

Result

<a href="?color=blue&size=L">Large</a>

Removing Parameters

Pass None to remove a parameter:

Template

{# If current URL is ?color=blue&size=M #}
<a href="{% querystring color=None %}">Clear color filter</a>

Result

<a href="?size=M">Clear color filter</a>

Handling Lists

If a value is a list, multiple parameters with the same key are output:

Variable

colors = ['red', 'blue']

Template

<a href="{% querystring color=colors %}">Red and Blue</a>

Result

<a href="?color=red&color=blue">Red and Blue</a>

Storing in a Variable

Use as to store the result in a variable:

Template

{% querystring page=page_obj.next_page_number as next_page_url %}
<a href="{{ next_page_url }}">Next</a>

Pagination Example

A common use case is pagination links that preserve other query parameters:

Template

{# Preserves filters like ?category=books while changing page #}
{% if page_obj.has_previous %}
  <a href="{% querystring page=page_obj.previous_page_number %}">Previous</a>
{% endif %}

{% if page_obj.has_next %}
  <a href="{% querystring page=page_obj.next_page_number %}">Next</a>
{% endif %}

Commentary

This is a fantastic addition to Django's template tags. Before querystring, preserving existing query parameters while modifying one or two was tedious and error-prone.

The most common use case is pagination. Previously, you had to manually reconstruct the query string or use a custom template tag. Now it's built in.

Note: Requires the django.template.context_processors.request context processor to be enabled (it is by default in new Django projects).


Did we get something wrong? Is there a use case for the querystring tag that we should add? Please let us know.

Send Feedback

Official Documentation
This page last updated on Dec. 3, 2025, 11:37 p.m. EST