2

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>' 
1
  • if "userName" in form:? Commented Jul 24, 2014 at 17:30

1 Answer 1

2

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"))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.