Skip to content

Instantly share code, notes, and snippets.

@scriptogre
Last active March 18, 2025 12:34
Show Gist options
  • Select an option

  • Save scriptogre/b3199035c04b4100d5727602e69a1b6c to your computer and use it in GitHub Desktop.

Select an option

Save scriptogre/b3199035c04b4100d5727602e69a1b6c to your computer and use it in GitHub Desktop.
Ports Django 5.1's `{% querystring %}` template tag functionality to Jinja2.
# config/jinja2.py
"""
Ports Django 5.1's `{% querystring %}` template tag (https://docs.djangoproject.com/en/5.1/releases/5.1/#querystring-template-tag)
to a Jinja2 global function for `django-jinja`.
Add this to `config/jinja2.py`, then in your settings file:
TEMPLATES = [
{
'BACKEND': 'django_jinja.jinja2.Jinja2',
'OPTIONS': {
'globals': {
'querystring': 'config.jinja2.querystring',
},
},
},
]
"""
from collections.abc import Iterable
from jinja2 import pass_context
@pass_context
def querystring(context, query_dict=None, **kwargs):
"""
Add, remove, and change parameters of a ``QueryDict`` and return the result
as a query string. If the ``query_dict`` argument is not provided, default
to ``request.GET``.
For example::
{{ querystring(foo=3) }}
To remove a key::
{{ querystring(foo=None) }}
To use with pagination::
{{ querystring(page=page_obj.next_page_number) }}
A custom ``QueryDict`` can also be used::
{{ querystring(my_query_dict, foo=3) }}
"""
if query_dict is None:
try:
query_dict = context['request'].GET
except KeyError as e:
msg = 'The `querystring` function requires `request` object in the context.'
raise KeyError(msg) from e
query_dict = query_dict.copy()
for key, value in kwargs.items():
if value is None:
if key in query_dict:
del query_dict[key]
elif isinstance(value, Iterable) and not isinstance(value, str):
query_dict.setlist(key, value)
else:
query_dict[key] = value
if not query_dict:
return ''
query_string = query_dict.urlencode()
return f'?{query_string}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment