简体   繁体   中英

Read a multidimensional post request using Django / Python

I'm sending a post request like this:

photo[1][id] = 1234
photo[1][size] = 4x4
photo[1][quantity] = 2
photo[2][id] = 4567
photo[2][size] = 4x6
photo[2][quantity] = 1
...

What is the best way to read this data using Django/Python?

Thanks!!

You might want to try querystring-parser .

For example, if you had the following form being submitted via POST to your view:

<input name="photo['1']['id']"       value="1234">
<input name="photo['1']['size']"     value="4x4">
<input name="photo['1']['quantity']" value="2">
<input name="photo['2']['id']"       value="4567">
<input name="photo['2']['size']"     value="4x6">
<input name="photo['2']['quantity']" value="1">

In your view you can parse it like this:

from querystring_parser import parser
post_dict = parser.parse(request.POST.urlencode())
print post_dict
# {u'csrfmiddlewaretoken': u'<crazy hash goes here>', 
#  u'photo': 
#    {1: {u'id': u'1234', u'size': u'4x4', u'quantity': u'2'},
#     2: {u'id': u'4567', u'size': u'4x6', u'quantity': u'1'}
#  }

Accessing the first photo's size is as simple as post_dic[1]['size']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM