-
-
Save clichedmoog/614f9c94cb747f156d94f9a5f97a4528 to your computer and use it in GitHub Desktop.
Django template tag to append a query string to a url
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment