how to loop through httprequest post variables in python


Question

How can you loop through the HttpRequest post variables in Django?

I have

for k,v in request.POST:
     print k,v

which is not working properly.

Thanks!

1
28
7/21/2010 9:14:41 PM

Accepted Answer

request.POST is a dictionary-like object containing all given HTTP POST parameters.

When you loop through request.POST, you only get the keys.

for key in request.POST:
    print(key)
    value = request.POST[key]
    print(value)

To retrieve the keys and values together, use the items method.

for key, value in request.POST.items():
    print(key, value)

Note that request.POST can contain multiple items for each key. If you are expecting multiple items for each key, you can use lists, which returns all values as a list.

for key, values in request.POST.lists():
    print(key, values)

For more information see the Django docs for QueryDict.

89
3/24/2016 5:28:47 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon