91👍
How about?
from django.http import QueryDict
ordinary_dict = {'a': 'one', 'b': 'two', }
query_dict = QueryDict('', mutable=True)
query_dict.update(ordinary_dict)
24👍
Python has a built in tool for encoding a dictionary (any mapping object) into a query string
params = {'a': 'one', 'b': 'two', }
urllib.urlencode(params)
'a=one&b=two'
http://docs.python.org/2/library/urllib.html#urllib.urlencode
QueryDict
takes a querystring as first param of its contstructor
def __init__(self, query_string, mutable=False, encoding=None):
q = QueryDict('a=1&b=2')
https://github.com/django/django/blob/master/django/http/request.py#L260
Update: in Python3, urlencode has moved to urllib.parse:
from urllib.parse import urlencode
params = {'a': 'one', 'b': 'two', }
urlencode(params)
'a=one&b=two'
- [Django]-Django development server reload takes too long
- [Django]-Django-way for building a "News Feed" / "Status update" / "Activity Stream"
- [Django]-Django 1.8 Run a specific migration
16👍
Actually a little indirect but more logical way to achieve this is using MultiValueDict.
This way multiple values per key can be stored in a QueryDict and .getlist method should then work fine.
from django.http.request import QueryDict, MultiValueDict
dictionary = {'my_age': ['23'], 'my_girlfriend_age': ['25', '27'], }
qdict = QueryDict('', mutable=True)
qdict.update(MultiValueDict(dictionary))
print qdict.get('my_age') # 23
print qdict['my_girlfriend_age'] # 27
print qdict.getlist('my_girlfriend_age') # ['25', '27']
- [Django]-Accepting email address as username in Django
- [Django]-Where is my Django installation?
- [Django]-How to access array elements in a Django template?
5👍
My solution works both for single and multiple key values:
def dict_to_querydict(dictionary):
from django.http import QueryDict
from django.utils.datastructures import MultiValueDict
qdict = QueryDict('', mutable=True)
for key, value in dictionary.items():
d = {key: value}
qdict.update(MultiValueDict(d) if isinstance(value, list) else d)
return qdict
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
- [Django]-A better way to restart/reload Gunicorn (via Upstart) after 'git pull'ing my Django projects
- [Django]-Django : Testing if the page has redirected to the desired url
0👍
I couldn’t be much more late to the party, but I recently needed to do the same – but to preserve the read-only behaviour of a ‘real’ QueryDict from a response object.
Adapting the code from QueryDict.fromkeys()
method gave a nice function:
from django.http import QueryDict
def querydict_from_dict(data: Dict[str, Any], mutable=False) -> QueryDict:
"""
Return a new QueryDict with keys (may be repeated) from an iterable and
values from value.
"""
q = QueryDict('', mutable=True)
for key in data:
q.appendlist(key, data[key])
if not mutable:
q._mutable = False
return q
- [Django]-Can django's auth_user.username be varchar(75)? How could that be done?
- [Django]-How to stop celery worker process
- [Django]-Django "login() takes exactly 1 argument (2 given)" error