1

This is my code:

    print """\
<form method="post">
    Please enter Viewer Type:<br />
<table>
"""

#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"
print """\
    <option value="C">Crowd Funding
    <option value="P">Premium
"""
#do it button

print """\
    <input type="submit" value="OK" />
"""

print """\
</form>
</body>
<html>
"""

ViewerType=form['ViewerType'].value

And, when I serve it to a browser, this is the error:

Traceback (most recent call last): File "/home/nandres/dbsys/mywork/James/mywork/ViewerForm.py", >line 42, in ViewerType=form['ViewerType'].value File "/usr/lib/python2.7/cgi.py", line 541, in >getitem raise KeyError, key KeyError: 'ViewerType'

And line 42 is the last line of my code.

The error isn't actually affecting functionality, and everything works fine, but I don't really want it popping up. Any advice/insight would be appreciated.

Btw, I have this at the top of my code:

import cgi
form = cgi.FieldStorage()

2 Answers 2

1

When your script is first called to render the page, the form dict is empty. The dict will only get filled when the user actually submits the form. So changing your HTML to

<option value="C" selected>Crowd Funding

won't help.

So you need to test the dict before you attempt to access it. Eg,

#! /usr/bin/env python

import cgi

form = cgi.FieldStorage()

print 'Content-type: text/html\n\n'

print "<html><body>"
print """\
<form method="post">
    Please enter Viewer Type:<br />
<table>
"""

#Viewer Type
print "<tr><td>Viewer Type<select name=""ViewerType"">"

print """\
    <option value="C">Crowd Funding
    <option value="P">Premium
"""
#do it button

print """\
    <input type="submit" value="OK" />
"""

print "</table></form>"

if len(form) > 0:
    ViewerType = form['ViewerType'].value
    print '<p>Viewer Type=' + ViewerType + '</p>'
else:
    print '<p>No Viewer Type selected yet</p>'

print "</body></html>"
2
  • Thanks mate, I used your code for inspiration and got it working. Oct 2, 2014 at 10:39
  • Excellent! Thanks for the points. PS. I hope your actual program is not serving HTML with missing closing tags, etc. :)
    – PM 2Ring
    Oct 2, 2014 at 10:44
0

Simple solution if you don't want it popping:

try:
    ViewerType=form['ViewerType'].value
except KeyError:
    pass

It'll work but I would recommend you to debug your code and find out why you are getting KeyError. From https://wiki.python.org/moin/KeyError,

Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.