Django - 获取POST返回值列表的字典 [英] Django - getting POST to return a dictionary where the values are lists
问题描述
被困在这一段时间:
我们有一个视图,其上有很多菜,如下所示:
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"
然而,我们似乎找不到一种方式给出成绩和评论的输入框同名,所以我们''得到一个POST字典,其中值是列表本身:
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"]
如果我们命名输入框和注释框两者html中的意大利面,POST只跟踪评论的第二件事情,而且成绩完全丧失,所以我们回来的是:
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!!
谢谢!
推荐答案
不幸的是,您只需要为每个成绩和评论使用不同的ID,然后做一些服务器端解析来很好地格式化数据。或者您可以进行客户端解析,并使用$ .post将JSON数据发送到服务器。我会倾向于第二个选择,老实说,尽管你仍然需要做一些服务器端验证/数据清理。
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);
}
}
这篇关于Django - 获取POST返回值列表的字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!