HTMLフォームの選択されたチェックボックスを取得し表示します。
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
選択されたチェックボックスを調べる
'''
html = '''Content-Type: text/html
<html>
<head>
<title>選択されたチェックボックスを取得する</title>
</head>
<body>
<h1>選択されたチェックボックスを取得する</h1>
<p>選択された値は、「%s」です。</p>
<form action="test07.cgi" method="post">
<input type="checkbox" name="python" value="python" id="python" />
<label for="python">python</label><br />
<input type="checkbox" name="perl" value="perl" id="perl" />
<label for="perl">perl</label><br />
<input type="checkbox" name="ruby" value="ruby" id="ruby" />
<label for="ruby">ruby</label><br />
<input type="submit" />
</form>
</body>
</html>
'''
import cgi
f = cgi.FieldStorage()
lst = []
if f.getfirst('python'):
lst.append('python')
if f.getfirst('perl'):
lst.append('perl')
if f.getfirst('ruby'):
lst.append('ruby')
print html % ','.join(lst)
import cgi
f = cgi.FieldStorage()
HTMLフォームから送信された値は、cgiモジュールのFieldStorageクラスを使用して取得します。
チェックボックスの値を取得するには、FieldStorageクラスの getfirst() を使用します。
if f.getfirst('python'):
lst.append('python')
チェックボックスが選択されていれば、チェックボックスの name 属性に対して value 属性の値が設定されます。
チェックボックスが選択されなければ、値は設定されません。
チェックボックスの name 属性に値が設定されているか調べます。
チェックボックス python が選択されていれば if f.getfirst('python') は True になるので、変数 lst に値を追加します。
同様に、perl と ruby に値が設定されているか調べ、変数 lst に追加します。
print html % ','.join(lst)
変数 lst には選択されたチェックボックスの値が設定されています。
lst の値を ,(カンマ) でつなぎ、文字列フォーマットの %s と置き換えて出力します。