Skip to content

Instantly share code, notes, and snippets.

@dgouldin
Created September 9, 2011 23:49
Show Gist options
  • Save dgouldin/1207636 to your computer and use it in GitHub Desktop.
Save dgouldin/1207636 to your computer and use it in GitHub Desktop.
Django templatetag to output the current page's querystring updated with the specified values.
from django import template
register = template.Library()
class UpdateQuerystringNode(template.Node):
def __init__(self, **kwargs):
self.kwargs = kwargs
def render(self, context):
query_dict = context['request'].GET.copy()
for k,v in self.kwargs.items():
query_dict[k] = v
return query_dict.urlencode()
@register.tag
def update_querystring(parser, token):
"""
From /?foo=bar, {% update_querystring foo=baz %}
will output foo=baz.
"""
bits = token.split_contents()
return UpdateQuerystringNode(**dict([bit.split('=') for bit in bits[1:]]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment