在Django视图中,我如何迭代表单字段

时间:2014-02-02 08:39:59

标签: python django

在Django视图中,我可以迭代由表单

发布的文件
def stack_register(request):
"""
"""

print(request)
print('type request: ', type(request))


if request.method == 'POST':

    for key in request.FILES.keys():
        print('key: ' + key)


return HttpResponse('received')

如何为其他表单字段执行相同的操作?

1 个答案:

答案 0 :(得分:-1)

可以通过在请求中打印元组来获得字段信息,但据我所知,获取值必须实际读取它们或事先知道密钥。

这就是我得到它的方式:

def stack_register(request):
"""
"""

print(request)
print('type request: ', type(request))


if request.method == 'POST':

    print('')

    for key in request.FILES.keys():
        print('key: ' + key)
        print('file_name: ' + str(request.FILES[key]))


    print('type', type(request.POST.items()))


    for tuple in request.POST.items():  #this was the probelmatic code
        print('tuple: ' + str(tuple))

    #keep syntax for list
    #library = request.POST.getlist('library')
    #print('library: ', library)

    library = request.POST.__getitem__('library')
    print('library: ', library)

    stack = request.POST.__getitem__('stack')
    print('stack: ', stack)

    time = request.POST.__getitem__('time')
    print('time: ', time)

    medium = request.POST.__getitem__('medium')
    print('medium: ', medium)

    comments = request.POST.__getitem__('comments')
    print('comments: ', comments)

    storage = request.POST.__getitem__('storage')
    print('storage: ', storage)   


return HttpResponse('received')

在我的书中,这比学习Django表格的狡猾方式,冗长乏味的文档要容易得多,并提供更多动手控制。

顺便说一句,对于所有文档缓冲区,我认为代码的最佳文档是编写简单明了的代码。