简体   繁体   中英

How do I iterate over the form values in python cgi ? Newbie

Let say i have a form with multiple fields. And in my cgi i am using this all values.For Example

res1 = form.getvalue("opt_1")
res2 = form.getvalue("opt_2")
res3 = form.getvalue("opt_3") 
res4 = form.getvalue("opt_4")
res5 = form.getvalue("opt_5")
       ...
       ...
res100 = form.getvalue("opt_100")

In my cgi , I am using a for loop to get the values

for i in range(1, 100):
    res[i] = form.getvalue('opt_[i]')
    print res[i]

I am getting an error: NameError: global name 'res' is not defined

There's two problems with your loop: first, res doesn't exist yet, so trying to assign to its items won't work. Second, if you create it as an empty list first, you can't expand it by writing past the end.

Fix both at once by using a list comprehension instead:

res = [form.getfirst('opt_{}'.format(i)) for i in range(1, 100)]

This puts the value of opt_1 at res[0] , and so on - if that is a problem, you could add a dummy element to the start of it:

res = [None] + [form.getfirst('opt_{}'.format(i)) for i in range(1, 100)]

or use a dictionary instead:

res = {i: form.getfirst('opt_{}'.format(i)) for i in range(1, 100)}

Note that, per the docs , you should avoid using getvalue , since it might return either a string or a list depending on user input. Use form.getfirst to instead guarantee that you will have a string.

Looks like you haven't defined res , define it first:

res = []
for i in range(1, 100):
    res.append(form.getvalue('opt_%d'%i))
    print res[i-1]

Where res will be a list containing the results of form.getvalue('opt_i') s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM