Skip to content

Instantly share code, notes, and snippets.

@sam-ghosh
Forked from leonsmith/url_add_query.py
Created April 1, 2019 11:32
Show Gist options
  • Save sam-ghosh/82779489981e322816630e7c0fcdd0e0 to your computer and use it in GitHub Desktop.
Save sam-ghosh/82779489981e322816630e7c0fcdd0e0 to your computer and use it in GitHub Desktop.
Django template tag to append a query string to a url
from urlparse 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()))
@BartlomiejSkwira
Copy link

For Python 3 replace

from urlparse import urlsplit, urlunsplit

with:

from urllib.parse import urlsplit, urlunsplit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment