Last active
August 30, 2016 09:32
-
-
Save avalanchy/d775bcc14a27d14b5a14c7a097af61fd to your computer and use it in GitHub Desktop.
Overwritten Django's reverse function which additionally allows to construct query string for an URL.
This file contains hidden or 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
def reverse_qs(*args, **kwargs): | |
"""Overwritten django reverse function which additionally allows | |
to construct query string for an URL. | |
New kwargs: | |
* `params` a normal python dict. | |
* `q_dict` a QueryDict instance. | |
* `q_string` a query string same as in URL. | |
Examples of usage: | |
>>> reverse_qs('example', params={'id': 123, 'tags': ['a', 'b']}) | |
http://example.com?id=123&tags=a&tags=b | |
>>> reverse_qs( | |
viewname='example', | |
q_dict=self.request.GET, # <QueryDict: {'old': ['false']}> | |
q_string='new=true', | |
) | |
http://example.com?new=true&old=false | |
""" | |
params = kwargs.pop('params', {}) | |
q_dict = kwargs.pop('q_dict', None) | |
q_string = kwargs.pop('q_string', '') | |
query_dict = QueryDict('', mutable=True) | |
if params: | |
query_dict.update(_dict_to_query_dict(params)) | |
if q_dict: | |
query_dict.update(q_dict) | |
if q_string: | |
query_dict.update(QueryDict(q_string)) | |
url = reverse(*args, **kwargs) | |
if query_dict: | |
query_string = query_dict.urlencode() | |
return '{}?{}'.format(url, query_string) | |
return url | |
def _dict_to_query_dict(params): | |
"""Converts python dict to django's QueryDict""" | |
query_dict = QueryDict('', mutable=True) | |
for key, value in params.iteritems(): | |
if value is None: | |
query_dict[key] = '' | |
elif isinstance(value, (int, long, float, basestring)): | |
query_dict[key] = value | |
elif isinstance(value, list): | |
query_dict.setlist(key, value) | |
else: | |
raise ValueError | |
return query_dict |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment