Skip to content

Instantly share code, notes, and snippets.

@BartlomiejSkwira
Forked from sam-ghosh/url_add_query.py
Last active October 9, 2020 09:37
Show Gist options
  • Save BartlomiejSkwira/554df59afffdf5e7040a02bc95b69ad0 to your computer and use it in GitHub Desktop.
Save BartlomiejSkwira/554df59afffdf5e7040a02bc95b69ad0 to your computer and use it in GitHub Desktop.
Django template tag to append a query string to a url - Python 3
# Python 3 version
from urllib.parse import urlsplit, urlunsplit
from django import template
from django.http import QueryDict
register = template.Library()
@register.simple_tag
def url_add_query(url, **kwargs):
"""
Lets you append a querystring to a url.
If the querystring argument is already present it will be replaced
otherwise it will be appended to the current querystring.
> url = 'http://example.com/?query=test'
> url_add_query(url, query='abc', foo='bar')
'http://example.com/?query=abc&foo=bar'
It also works with relative urls.
> url = '/foo/?page=1'
> url_add_query(url, query='abc')
'/foo/?query=abc&page=1'
and blank strings
> url = ''
> url_add_query(url, page=2)
'?page=2'
"""
parsed = urlsplit(url)
querystring = QueryDict(parsed.query, mutable=True)
querystring.update(kwargs)
return urlunsplit(parsed._replace(query=querystring.urlencode()))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment