Skip to content

Instantly share code, notes, and snippets.

@benbacardi
Last active August 25, 2024 23:07
Show Gist options
  • Save benbacardi/d6cd0fb8c85e1547c3c60f95f5b2d5e1 to your computer and use it in GitHub Desktop.
Save benbacardi/d6cd0fb8c85e1547c3c60f95f5b2d5e1 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.items():
query[k] = v
return query.urlencode()
@Hammy27
Copy link

Hammy27 commented Mar 18, 2021

If you are working with djangos pagination and your template takes care of the page keyword, simply adding

query.pop('page', None)

before returning the query does the trick.

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