Login

Template tags/filter for working with query strings

Author:
gonz
Posted:
January 18, 2008
Language:
Python
Version:
.96
Score:
5 (after 5 ratings)

Some template tags/filter for working with query strings in templates.

Examples:

{% load qstring %}

{% qstring %} # Prints current request's query string
{% qstring as current_qstring %} # Same but goes to context

{{ current_qstring|qstring_del:"key1" }} # Deletes all key1 values
{{ current_qstring|qstring_del:"key1&key2" }} # Deletes all key1 and key2values

{{ current_qstring|qstring_set:"key1=1&key2=2" }} # Deletes all old key1 and key2 values and adds the new values.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
"""
Templatetags/filters for working with query strings

version: 0.3
"""
from django import template
from django.http import QueryDict


class GetRequestQueryStringNode(template.Node):
    def __init__(self, asvar=None):
        self.asvar = asvar

    def __repr__(self):
        return '<GetRequestQueryStringNode>'

    def render(self, context):
        request = context.get('request', None)
        if request is None:
            return ''
        qstring = request.GET.urlencode()
        if self.asvar:
            context[self.asvar] = qstring
            return ''
        return qstring


def qstring(parser, token):
    """
    Get the current request's query string.

    USAGE: {% qstring %} or {% qstring as current_qstring %}
    """
    bits = token.split_contents()
    if len(bits) not in (1, 3):
        raise template.TemplateSyntaxError("'%s' takes zero or 2 arguments "
                                           "(as var_name)." % bits[0])
    if len(bits) == 1:
        asvar = None
    else:
        asvar = bits[2]
    return GetRequestQueryStringNode(asvar)


def _qdict_del_keys(qdict, del_qstring):
    for key in del_qstring.split('&'):
        try:
            del qdict[key]
        except KeyError:
            pass
    return qdict


def _qdict_set_keys(qdict, set_qstring):
    set_qdict = QueryDict(set_qstring)
    for key, values in set_qdict.items():
        qdict[key] = set_qdict[key]
    return qdict


def qstring_del(qstring, del_qstring):
    """
    Returns a query string w/o some keys, every value for each key gets deleted.

    More than one key can be specified using an & as separator:

    {{ my_qstring|qstring_del:"key1&key2" }}
    """
    qdict = QueryDict(qstring, mutable=True)
    return _qdict_del_keys(qdict, del_qstring).urlencode()


def qstring_set(qstring, set_qstring):
    """
    Updates a query string, old values get deleted.

    {{ my_qstring|qstring_set:"key1=1&key1=2&key2=3" }}
    """
    qdict = QueryDict(qstring, mutable=True)
    return _qdict_set_keys(qdict, set_qstring).urlencode()


register = template.Library()
register.tag(qstring)
register.filter('qstring_del', qstring_del)
register.filter('qstring_set', qstring_set)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

Please login first before commenting.