How to add the current query string to an URL in a Django template?
To capture the QUERY_PARAMS that were part of the request, you reference the dict that contains those parameters (request.GET
) and urlencode them so they are acceptable as part of an href. request.GET.urlencode
returns a string that looks like ds=&date_published__year=2008
which you can put into a link on the page like so:
<a href="sameLink/?{{ request.GET.urlencode }}">
If you register a templatetag like follows:
@register.simple_tag
def query_transform(request, **kwargs):
updated = request.GET.copy()
updated.update(kwargs)
return updated.urlencode()
you can modify the query string in your template:
<a href="{% url 'view_name' %}?{% query_transform request a=5 b=6 %}">
This will preserve anything already in the query string and just update the keys that you specify.
I found that @Michael's answer didn't quite work when you wanted to update an existing query parameter.
The following worked for me:
@register.simple_tag
def query_transform(request, **kwargs):
updated = request.GET.copy()
for k, v in kwargs.items():
updated[k] = v
return updated.urlencode()