Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting items out of a QueryDict

Tags:

python

django

I have a querydict that looks like the following:

<QueryDict: {u'{"content":"aa","id":"1"}': [u'']}>

How would I extract out id?

I have tried doing queryDictExample.get("id"), but it didn't work.

like image 931
egidra Avatar asked Apr 05 '12 05:04

egidra


4 Answers

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.

like image 145
Daniel Roseman Avatar answered Oct 16 '22 05:10

Daniel Roseman


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: somename
data: abcdefg
like image 12
SpiRail Avatar answered Oct 16 '22 04:10

SpiRail


This works for multiple values:

dict(MyDict.lists())

Dict keys are query vars, and dict values are lists of query values.

like image 8
frnhr Avatar answered Oct 16 '22 05:10

frnhr


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).

like image 3
Adarsh Srivastava Avatar answered Oct 16 '22 03:10

Adarsh Srivastava