2024-04-24 20:00:15 发布
网友
在PHP中,我这样做是为了将name作为数组。
name
<input type"text" name="name[]" /> <input type"text" name="name[]" />
或者如果我想将name作为关联数组:
<input type"text" name="name[first]" /> <input type"text" name="name[last]" />
这类东西的Django等价物是什么?
Check out the QueryDict documentation,特别是^{}的用法。
由于视图中的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>
然后像这样:
def mypath(request): if request.method == 'POST': greetings = request.POST.getlist('hi') # will be ['heya1','heya2']
Django不提供从请求对象获取关联数组(Python中的字典)的方法。正如第一个答案所指出的,您可以根据需要使用.getlist(),或者编写一个函数,该函数可以接受QueryDict,并根据您的喜好重新组织它(例如,如果键与某些key[*]模式匹配,则拉出键/值对)。
.getlist()
QueryDict
key[*]
很抱歉发现了这个问题,但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']}}}
唯一的区别是你用圆点代替括号。
编辑:此机制已被表单前缀替换,但如果仍要使用此概念,可以在应用程序中删除以下旧代码: https://gist.github.com/grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60
Check out the QueryDict documentation,特别是^{} 的用法。
由于视图中的request.POST和request.GET是QueryDict的实例,因此可以执行以下操作:
然后像这样:
Django不提供从请求对象获取关联数组(Python中的字典)的方法。正如第一个答案所指出的,您可以根据需要使用
.getlist()
,或者编写一个函数,该函数可以接受QueryDict
,并根据您的喜好重新组织它(例如,如果键与某些key[*]
模式匹配,则拉出键/值对)。很抱歉发现了这个问题,但Django有一个utils.datastructures.DotExpandedDict。这是一份文件:
唯一的区别是你用圆点代替括号。
编辑:此机制已被表单前缀替换,但如果仍要使用此概念,可以在应用程序中删除以下旧代码: https://gist.github.com/grzes/73142ed99dc8ad6ac4fc9fb9f4e87d60
相关问题 更多 >
编程相关推荐