10 | | from django.http import QueryDict |
11 | | |
12 | | register = template.Library() |
13 | | |
14 | | |
15 | | @register.simple_tag |
16 | | def build_query(**kwargs): |
17 | | """Build a query string""" |
18 | | query_dict = QueryDict(mutable=True) |
19 | | |
20 | | for k, v in kwargs.items(): |
21 | | if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types): |
22 | | query_dict.setlist(k, v) |
23 | | else: |
24 | | query_dict[k] = v |
25 | | |
26 | | return query_dict.urlencode() |
27 | | |
28 | | |
29 | | @register.simple_tag(takes_context=True) |
30 | | def set_query_values(context, **kwargs): |
31 | | """Override existing parameters in the current query string""" |
32 | | query_dict = context.request.GET.copy() |
33 | | |
34 | | for k, v in kwargs.items(): |
35 | | if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types): |
36 | | query_dict.setlist(k, v) |
37 | | else: |
38 | | query_dict[k] = v |
39 | | |
40 | | return query_dict.urlencode() |
41 | | |
42 | | |
43 | | @register.simple_tag(takes_context=True) |
44 | | def append_query_values(context, **kwargs): |
45 | | """Append to existing parameters in the current query string""" |
46 | | query_dict = context.request.GET.copy() |
47 | | |
48 | | for k, v in kwargs.items(): |
49 | | if isinstance(v, collections.Iterable) and not isinstance(v, six.string_types): |
50 | | for v_item in v: |
51 | | query_dict.appendlist(k, v_item) |
52 | | else: |
53 | | query_dict.appendlist(k, v) |
54 | | |
55 | | return query_dict.urlencode() |
56 | | }}} |
| 5 | [https://pastebin.com/vJ3feNvY] |