You can't change the request. GET or request. POST as they are instances of QueryDict which are immutable according to the docs: QueryDict instances are immutable, unless you create a copy() of them.
In an HttpRequest object, the GET and POST attributes are instances of django. http. QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.
New in Django >= 1.4.
QueryDict.dict()
https://docs.djangoproject.com/en/stable/ref/request-response/#django.http.QueryDict.dict
This should work: myDict = dict(queryDict.iterlists())
This is what I've ended up using:
def qdict_to_dict(qdict):
"""Convert a Django QueryDict to a Python dict.
Single-value fields are put in directly, and for multi-value fields, a list
of all values is stored at the field's key.
"""
return {k: v[0] if len(v) == 1 else v for k, v in qdict.lists()}
From my usage this seems to get you a list you can send back to e.g. a form constructor.
EDIT: maybe this isn't the best method. It seems if you want to e.g. write QueryDict
to a file for whatever crazy reason, QueryDict.urlencode()
is the way to go. To reconstruct the QueryDict
you simply do QueryDict(urlencoded_data)
.
from django.utils import six
post_dict = dict(six.iterlists(request.POST))
If you do not want the values as Arrays you can do the following:
# request = <QueryDict: {u'key': [u'123ABC']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"123ABC" }
# Only work for single item lists
# request = <QueryDict: {u'key': [u'123ABC',U 'CDEF']}>
dict(zip(request.GET.keys(), request.GET.values()))
{u'key': u"CDEF" }
zip is a powerful tool read more about it here http://docs.python.org/2/library/functions.html#zip
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With