Last active
December 14, 2015 18:09
-
-
Save hirokiky/5127752 to your computer and use it in GitHub Desktop.
Django's template filters for prams (QueryDict's instance). - query_string: Takes QueryDict's instance and argument. It returns a querystirng only including the values specified by argument. The argument should be constructed by query names separated by spaces.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from urllib import urlencode | |
from django.template import Library | |
register = Library() | |
@register.filter(name='query_string' | |
def query_string(value, arg): | |
""" | |
Takes QueryDict's instance and argument. | |
It returns a querystirng only including the values | |
specified by argument. | |
The argument should be constructed by query names | |
separated by spaces. | |
Usage: | |
{{ params|query_string:'page next' }} | |
then, it will be | |
'page=2&next=/' | |
even thogh the params contains `'number': [123]` for example. | |
""" | |
def dict_filter(dict_, included): | |
d = dict_.copy() | |
for k in dict_.keys(): | |
if k not in included: | |
try: | |
d.pop(k) | |
except KeyError: | |
pass | |
return d | |
if not isinstance(value, (dict, QueryDict)): | |
return "" | |
included = arg.split() | |
filtered = dict_filter(value, included) | |
if isinstance(filtered, QueryDict): | |
items = filtered.iterlists() | |
else: | |
items = filtered.items() | |
output = [] | |
for k, list_ in items: | |
output.extend([urlencode({k: v}) for v in list_]) | |
return '&'.join(output) | |
query_string.is_safe = True |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment