public
Last active

Django templatetag to output the current page's querystring updated with the specified values.

  • Download Gist
gistfile1.py
Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
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:]]))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.