python Django 相当于 PHP 的表单值数组/关联数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/801354/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:53:06  来源:igfitidea点击:

Django equivalent of PHP's form value array/associative array

pythondjangoforms

提问by Imran

In PHP, I would do this to get nameas an array.

在 PHP 中,我会这样做以获得name一个数组。

<input type"text" name="name[]" />
<input type"text" name="name[]" />

Or if I wanted to get nameas an associative array:

或者,如果我想获得name一个关联数组:

<input type"text" name="name[first]" />
<input type"text" name="name[last]" />

What is the Django equivalent for such things?

什么是 Django 等价物?

回答by Paolo Bergantino

Check out the QueryDict documentation, particularly the usage of QueryDict.getlist(key).

查看 QueryDict 文档,特别是QueryDict.getlist(key).

Since request.POST and request.GET in the view are instances of QueryDict, you could do this:

由于视图中的 request.POST 和 request.GET 是 QueryDict 的实例,您可以这样做:

<form action='/my/path/' method='POST'>
<input type='text' name='hi' value='heya1'>
<input type='text' name='hi' value='heya2'>
<input type='submit' value='Go'>
</form>

Then something like this:

然后是这样的:

def mypath(request):
    if request.method == 'POST':
        greetings = request.POST.getlist('hi') # will be ['heya1','heya2']

回答by gzy

Sorry for digging this up, but Django has an utils.datastructures.DotExpandedDict. Here's a piece of it's docs:

很抱歉挖掘这个问题,但 Django 有一个 utils.datastructures.DotExpandedDict。这是它的一部分文档:

>>> d = DotExpandedDict({'person.1.firstname': ['Simon'], \
        'person.1.lastname': ['Willison'], \
        'person.2.firstname': ['Adrian'], \
        'person.2.lastname': ['Holovaty']})
>>> d
{'person': {'1': {'lastname': ['Willison'], 'firstname': ['Simon']}, '2': {'lastname': ['Holovaty'], 'firstname': ['Adrian']}}}

The only difference being you use dot's instead of brackets.

唯一的区别是您使用点而不是括号。

EDIT: This mechanism was replaced by form prefixes, but here's the old code you can drop in your app if you still want to use this concept: https://gist.github.com/grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60

编辑:此机制已被表单前缀取代,但如果您仍想使用此概念,则可以将其放入应用程序中的旧代码:https: //gist.github.com/grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60

回答by Grant

Django does not provide a way to get associative arrays (dictionaries in Python) from the request object. As the first answer pointed out, you can use .getlist()as needed, or write a function that can take a QueryDictand reorganize it to your liking (pulling out key/value pairs if the key matches some key[*]pattern, for example).

Django 没有提供从请求对象中获取关联数组(Python 中的字典)的方法。正如第一个答案所指出的,您可以.getlist()根据需要使用,或者编写一个函数,该函数可以QueryDict根据自己的喜好重新组织它(key[*]例如,如果键匹配某个模式,则提取键/值对)。