Django等价于PHP的表单值数组/关联数组
问题描述:
在PHP中,我将这样做以名称
作为数组。
In PHP, I would do this to get name
as an array.
<input type"text" name="name[]" />
<input type"text" name="name[]" />
或者如果我想获得名称
一个关联数组:
Or if I wanted to get name
as an associative array:
<input type"text" name="name[first]" />
<input type"text" name="name[last]" />
Django等同于这样的东西是什么?
What is the Django equivalent for such things?
答
检查查询QueryDict文档,特别是使用 QueryDict.getlist(key)
。
Check out the QueryDict documentation, particularly the usage of QueryDict.getlist(key)
.
由于request.POST和request.GET在视图中是QueryDict的实例,您可以这样做:
Since request.POST and request.GET in the view are instances of QueryDict, you could do this:
<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>
然后这样:
def mypath(request):
if request.method == 'POST':
greetings = request.POST.getlist('hi') # will be ['heya1','heya2']