How to add the current query string to an URL in a Django template?
When I load a page, there is a link "sameLink" that I want to append to it the query string of its containing page.
I have following URL:
somedomain/reporting/article-by-month?variable1=2008
How can I do that?
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.