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?
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?
Informed by other answers but not needing the request passed in and only updates existing parameters.
@register.simple_tag(takes_context=True)
def querystring(context, **kwargs):
"""
Creates a URL (containing only the querystring [including "?"]) derived
from the current URL's querystring, by updating it with the provided
keyword arguments.
Example (imagine URL is ``/abc/?gender=male&name=Tim``)::
{% querystring "name"="Diego" "age"=20 %}
?name=Diego&gender=male&age=20
"""
request = context['request']
updated = request.GET.copy()
for k, v in kwargs.items(): # have to iterate over and not use .update as it's a QueryDict not a dict
updated[k] = v
return '?{}'.format(updated.urlencode()) if updated else ''
Just a workaround if you don't want loops or string concatenations.
String representation of url is something like '<WSGIRequest: GET \'our_url\'>'
So if you want our_url, you just need to use regex for it.
our_url = re.search(r'\/.*(?=\'>)', str(request)).group()