diff options
| author | Tom Carrick <tom@carrick.eu> | 2023-10-15 22:01:35 +0200 |
|---|---|---|
| committer | Mariusz Felisiak <felisiak.mariusz@gmail.com> | 2023-10-26 09:57:21 +0200 |
| commit | e67d3580edbee1a4b58d40875293714ac3fc6937 (patch) | |
| tree | 1299d0a74e11e3d5f6039459510cd12f73985078 /django/template | |
| parent | 718b32c6918037cfc746d7867333d79a3c887a8c (diff) | |
Fixed #10941 -- Added {% query_string %} template tag.
Diffstat (limited to 'django/template')
| -rw-r--r-- | django/template/defaulttags.py | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/django/template/defaulttags.py b/django/template/defaulttags.py index 79c10232bb..188bdf8c05 100644 --- a/django/template/defaulttags.py +++ b/django/template/defaulttags.py @@ -10,6 +10,7 @@ from itertools import groupby from django.conf import settings from django.utils import timezone from django.utils.html import conditional_escape, escape, format_html +from django.utils.itercompat import is_iterable from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe @@ -1167,6 +1168,46 @@ def now(parser, token): return NowNode(format_string, asvar) +@register.simple_tag(takes_context=True) +def query_string(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:: + + {% query_string foo=3 %} + + To remove a key:: + + {% query_string foo=None %} + + To use with pagination:: + + {% query_string page=page_obj.next_page_number %} + + A custom ``QueryDict`` can also be used:: + + {% query_string my_query_dict foo=3 %} + """ + if query_dict is None: + query_dict = context.request.GET + 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 is_iterable(value) 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}" + + @register.tag def regroup(parser, token): """ |
