Anna Presnyakova
Anna Presnyakova

Reputation: 93

Working in Python cgi with form. Empty input error

I am trying to work with forms on python and I have 2 problems which I can't decide for a lot of time.

First if I leave the text field empty, it will give me an error. url like this:

http://localhost/cgi-bin/sayHi.py?userName=

I tried a lot of variants like try except, if username in global or local and ect but no result, equivalent in php if (isset(var)). I just want to give a message like 'Fill a form' to user if he left the input empty but pressed button Submit.

Second I want to leave what was printed on input field after submit(like search form). In php it's quite easy to do it but I can't get how to do it python

Here is my test file with it

#!/usr/bin/python
import cgi 
print "Content-type: text/html \n\n" 
print """
<!DOCTYPE html >
<body>  
<form action = "sayHi.py" method = "get"> 
<p>Your name?</p> 
<input type = "text" name = "userName" /> <br>
Red<input type="checkbox" name="color" value="red">
Green<input type="checkbox" name="color" value="green">
<input type = "submit" /> 
</form> 
</body> 
</html> 
"""
form = cgi.FieldStorage() 
userName = form["userName"].value 
userName = form.getfirst('userName', 'empty')
userName = cgi.escape(userName)
colors = form.getlist('color')

print "<h1>Hi there, %s!</h1>" % userName 
print 'The colors list:'
for color in colors:
    print '<p>', cgi.escape(color), '</p>' 

Upvotes: 2

Views: 3398

Answers (1)

Robᵩ
Robᵩ

Reputation: 168596

On the cgi documentation page are these words:

The FieldStorage instance can be indexed like a Python dictionary. It allows membership testing with the in operator

One way to get what you want is to use the in operator, like so:

form = cgi.FieldStorage()

if "userName" in form:
    print "<h1>Hi there, %s!</h1>" % cgi.escape(form["userName"].value)

From the same page:

The value attribute of the instance yields the string value of the field. The getvalue() method returns this string value directly; it also accepts an optional second argument as a default to return if the requested key is not present.

A second solution for you might be:

print "<h1>Hi there, %s!</h1>" % cgi.escape(form.getvalue("userName","Nobody"))

Upvotes: 2

Related Questions