Search code examples
pythonhtmlcgitracebackkeyerror

KeyError in Python


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()

Solution

  • 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>"