Extracting Items Out Of A Querydict
Solution 1:
It seems like your client is posting JSON rather than formencoded data. Instead of accessing request.POST
, use request.body
(request.raw_post_data
in versions 1.3 or less) and use json.loads()
to convert to a dict.
Solution 2:
Maybe this doesn't fully apply to you. But when I searched for this, your question was the first Stackoverflow question.
I just wanted to get basic POST data out in Django. So just using GET worked fine for me. As the others stated, it might be easier to better format whatever script is creating the query.
Basically I have a AJAX doing a post towards Django, the POST looks a bit like this:
params = name=somename&data=abcdefg
http.send(params);
then in my view.py, i did this :
def somefuntion(request):
if request.method == 'POST':
log.info('POST applied')
alldata=request.POST
log.debug(alldata)
data = alldata.get("data", "0")
name = alldata.get("name", "0")
log.info("POST name: " + name)
log.info("POST data: " + data)
The output of alldata was :
<QueryDict: {u'data': [u'abcdefg'], u'name': [u'somename']}>
and the get commands give :
name: somenamedata: abcdefg
Solution 3:
This works for multiple values:
dict(MyDict.lists())
Dict keys are query vars, and dict values are lists of query values.
Solution 4:
You can use - request.data.get("content")
This will give you the data directly if in front end (jQuery,Angular) you have NOT used JSON.stringify(data)
.
Solution 5:
Encountered similar case recently where data from POST call was in QueryDict
form,
I was able to access value of particular key using
qdict.get(keyname)
Also I was able to iterate using QueryDict.items()
to get tuple of key & value
for q in qdict.items():
print(q)
Note that QueryDict
is subclass of Dictionary
so all standard methods of Dictionary
can also be implemented on QueryDict
.
More information available on djangoproject documentation https://docs.djangoproject.com/en/3.0/ref/request-response/#django.http.QueryDict
Post a Comment for "Extracting Items Out Of A Querydict"