Newbie Question - Checkboxes

Peter Otten __peter__ at web.de
Sun Dec 10 03:12:16 EST 2006


Leanne wrote:

> I have been using Python for only a few months part-time and have
> recently had my first encounter with retrieving user input from
> checkboxes.  I have a problem with the way Python reads the input
> values from a set of checkboxes on a webpage.
> 
> The values assigned to the checkboxes are integers.  I first of all
> check for a key of CHK_CHILDREN to see if any checkboxes have been
> checked.  That works fine.

Checkboxes can be in Tkinter, wxPython, anything...
Try to read your post from the addressees' perspective before you hit
[Send].
 
> I then use a 'for x in CHK_CHILDREN' loop to get all the values from
> the returned list.  This works for most cases except one.  If the user
> only checks 1 checkbox, Python reads a scalar, not a list, and if this
> scalar is a double digit integer (eg 11), then the loop goes through
> each digit and retrieves these values, eg retrieves 1 and then
> retrieves 1 again.
> 
> I have created a not so elegant work-around that names each checkbox a
> different name and therefore I know a scalar is returned each time, but
> was wondering if anyone knows what's going here.

Are you perchance using the cgi module? If so, the following tip from the
documentation may be helpful:

http://docs.python.org/dev/lib/node558.html

"""
If the submitted form data contains more than one field with the same name,
the object retrieved by "form[key]" is not a FieldStorage or
MiniFieldStorage instance but a list of such instances. Similarly, in this
situation, "form.getvalue(key)" would return a list of strings. If you
expect this possibility (when your HTML form contains multiple fields with
the same name), use the getlist() function, which always returns a list of
values (so that you do not need to special-case the single item case). For
example, this code concatenates any number of username fields, separated by
commas: 


value = form.getlist("username")
usernames = ",".join(value)
"""

Peter




More information about the Python-list mailing list