简体   繁体   English

解析JSON与键值-值(django / python)

[英]Parsing JSON with key-value-value (django/python)

I am making an RSVP form where the invitee can opt to bring a guest (or 2 or 3). 我正在制作RSVP表格,被邀请者可以选择带一位客人(或2或3)。 The form has inputs generated x number of times, where x is the # of guests the user sets. 表单的输入生成了x次,其中x是用户设置的访客数。 So for example, if the user chooses "0" from the dropdown, they're not bringing a guest so the form only has inputs for 1 person (themselves). 因此,例如,如果用户从下拉列表中选择“ 0”,则他们不会带客人,因此该表单仅包含1个人(自己)的输入。 If they select "1" from the dropdown, the form duplicates all the fields, but there is still just one route/one submit button. 如果他们从下拉列表中选择“ 1”,则该表单将复制所有字段,但是仍然只有一个路由/一个提交按钮。 The duplicated form fields are identical to the original, so the form has 2 inputs named "name", 2 inputs named "dinner", etc. 重复的表单字段与原始字段相同,因此该表单有2个名为“ name”的输入,2个名为“ dinner”的输入,依此类推。

I get a dictionary when I print request.POST: 我在打印请求时收到字典。

<QueryDict: {u'restrictions': [u'None', u'Gluten'], u'name': [u'Krista', u'Joel'], u'dinner': [u'chicken', u'fish'], u'csrfmiddlewaretoken': [u'iEjxo6KgLGHZWwvaxEd6I7CUd7GTs89VGpiKwmiCP9xqXKFK096s0vboK4pPQxea']}>

In vanilla python I can access the values like so: 在香草python中,我可以像这样访问值:

dictionary['restrictions'][1] 

which returns "Gluten". 返回“面筋”。 But in Django this expression returns 'e' - the letter at index 1 of the key name 'restrictions'. 但是在Django中,此表达式返回'e'-键名'restrictions'的索引1处的字母。 Likewise, 同样

for key, val1, val2 
   print key, val1, val2 

returns "too many values to unpack", presumably because it's unpacking the letters in the key name instead of the values. 返回“要解包的值太多”,大概是因为它正在解压缩键名中的字母而不是值。

How can I access the values? 如何访问这些值? Alternatively, is there a better way to generate multiple forms based on the user's selection, with just one route and one submit button? 或者,是否有更好的方法可以根据用户的选择,仅用一条路线和一个提交按钮来生成多种形式?

您应该尝试request.POST.getlist('restrictions')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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