Django - getting POST to return a dictionary where the values are lists

余生颓废 提交于 2020-01-15 05:14:25

问题


been stuck on this one for a while:

We've got a view that has a number of dishes on it, like this:

spaghetti
tacos
burger

we want to have the user be able to enter two pieces of information related to each dish, a grade and a comment. for example

spaghetti: 20, "tasty"
tacos: 10, "nasty"

however, we can't seem to find a way to give the input boxes for the grade and the comment the same name so we'd get back a POST dictionary where the values are lists themselves:

spaghetti: [20,"tasty"]
tacos:  [10, "nasty"]

if we name the input box and the comment box both "spaghetti" in the html form, then POST only tracks the second thing which is the comment, and the grade is completely lost, so all we get back is:

spaghetti: "tasty"
tacos: "nasty"

let us know what we're doing wrong!!

thanks!


回答1:


Unfortunately, you're just going to have to use a different id for each grade and comment, then do some server side parsing to format your data nicely. Either that or you can do client side parsing and use a $.post to send JSON data to the server. I'd lean towards the second option, honestly, although you'll still have to do some server side validation/data sanitization.

If you go for the second option, you could do something like this:

<div id='spaghetti'>
  <input field-type='grade' />
  <input field-type='comment' />
</div>

<script>
  $(document).ready(function() {
    $('input[type=submit]').click(function() {
      var data = {}
      var grade = $('#spaghetti').children('input[field-type=grade]').first().val();
      var comment = $('#spaghetti').children('input[field-type=comment]').first().val();
      data['spaghetti'] = [grade, comment];
      $.post('url', data);
    }
  }



回答2:


In the form, name one spaghetti_grade and another spaghetti_taste. Then you can access them using:

request.POST.get('spaghetti_grade','') and request.POST.get('spaghetti_taste','')

that will allow you to get both without the need for a list. You can then do the same for the other foods.



来源:https://stackoverflow.com/questions/18038261/django-getting-post-to-return-a-dictionary-where-the-values-are-lists

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!