help: Problem with cgi form

Max M maxm at mxm.dk
Mon Feb 25 16:40:01 EST 2002


netvegetable wrote:

> I have a hidden input on a cgi form... 
> 
>     print '<INPUT TYPE=HIDDEN NAME= "last_pos" VALUE=',last_byte_pos,'>'
> 
> I need the VALUE to be the  variable "last_byte_pos", but unfortunately 
> when I run the script for the first time the script crashes because it's 
> undeclared. 
> 
> What subroutine do I use to check if last_byte_pos is undeclared, and 
> assign it a default value if it is? 

Somehow I have the feeling that you are asking in east and I am 
answering in west, but here goes :-)

last_byte_pos = locals().get('last_byte_pos', 'defaultValue')

But this is a stupid and redundant way to do it!

Usually you just declare it in your program like:

last_byte_pos = 'defaultValue'

And then print it to the form like:

print '<INPUT TYPE=HIDDEN NAME= "last_pos" VALUE='%s'>' % last_byte_pos

Btw. If you are trying to keep state (keeping the variables value via a 
form) it is a good idea to call it the same thing in the form as in your 
script. It is a lot easier to remember :-)

like:

print '<INPUT TYPE=HIDDEN NAME= "last_byte_pos" VALUE='%s'>' % last_byte_pos

Then you can get the also get the variable again from the form via:

import cgi
form = cgi.FieldStorage()
if form.has_key('last_byte_pos'):
     last_byte_pos = form['last_byte_pos'].value
else:
     last_byte_pos = 'defaultValue'

And this last snippet is probably what you meant all along.

regards Max M




More information about the Python-list mailing list