Skip to content

Instantly share code, notes, and snippets.

@DmytroLitvinov
Created February 8, 2017 07:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DmytroLitvinov/30d5369dc0f08142f633d7bd26508ebd to your computer and use it in GitHub Desktop.
Save DmytroLitvinov/30d5369dc0f08142f633d7bd26508ebd to your computer and use it in GitHub Desktop.
Django query_transform templatetag
from django import template
register = template.Library()
@register.simple_tag(takes_context=True)
def query_transform(context, **kwargs):
'''
Returns the URL-encoded querystring for the current page,
updating the params with the key/value pairs passed to the tag.
E.g: given the querystring ?foo=1&bar=2
{% query_transform bar=3 %} outputs ?foo=1&bar=3
{% query_transform foo='baz' %} outputs ?foo=baz&bar=2
{% query_transform foo='one' bar='two' baz=99 %} outputs ?foo=one&bar=two&baz=99
A RequestContext is required for access to the current querystring.
'''
query = context['request'].GET.copy()
for k, v in kwargs.iteritems():
query[k] = v
return query.urlencode()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment