如何在python web.py中使用单选按钮

时间:2012-10-10 09:49:20

标签: python radio-button web.py

我正在使用web.py框架来创建一个简单的Web应用程序

我想创建一个单选按钮,所以我编写了以下代码

from web import form
from web.contrib.auth import DBAuth
import MySQLdb as mdb



render = web.template.render('templates/')

urls = (
  '/project_details',  'Project_Details',  
)

class Project_Details:

    project_details = form.Form( 
        form.Radio('Home Page'),
        form.Radio('Content'),
        form.Radio('Contact Us'),
        form.Radio('Sitemap'),
        )

    def GET(self):
        project_details = self.project_details()
        return render.projectdetails(project_details)  

当我使用网址localhost:8080运行代码时,我看到了以下错误

Traceback (most recent call last):
  File "/usr/lib/python2.7/site-packages/web/application.py", line 237, in process
    return p(lambda: process(processors))
  File "/usr/lib/python2.7/site-packages/web/application.py", line 565, in processor
    h()
  File "/usr/lib/python2.7/site-packages/web/application.py", line 661, in __call__
    self.check(mod)
  File "/usr/lib/python2.7/site-packages/web/application.py", line 680, in check
    reload(mod)
  File "/home/local/user/python_webcode/index.py", line 68, in <module>
    class Project_Details:
  File "/home/local/user/python_webcode/index.py", line 72, in Project_Details
    form.Radio('password'),
TypeError: __init__() takes at least 3 arguments (2 given)

需要在单选按钮中传递什么参数才能避免此错误

2 个答案:

答案 0 :(得分:1)

查看source,您似乎必须为所有项目使用一个Radio构造函数,因为相同的Radio对象实际上会生成多个<input>元素

尝试类似::

的内容
project_details = form.Form( 
    form.Radio('details', ['Home Page', 'Content', 'Contact Us', 'Sitemap']),
    )

答案 1 :(得分:0)

这就是我能够解密的。 checked ='checked'似乎是在列表中选择一个随机(最后?)项。如果没有默认选择,那么如果没有选择任何单选按钮,我的测试将返回NoneType。

project_details = form.Form(
  form.Radio('selections', ['Home Page', 'Content', 'Contact Us','Sitemap'], checked='checked'),
  form.Button("Submit") 
)

要以字符串形式访问用户选择...

result = project_details['selections'].value

如果您希望在模板处于活动状态时使用javascript,则可以在Radio行项目的末尾添加onchange ='myFunction()'。我还要为每个元素分配一个ID,以避免因getElementById调用而感到沮丧,因此我的声明如下所示。

 project_details = form.Form(
   form.Radio('selections', ['Home Page', 'Content', 'Contact Us','Sitemap'], checked='checked', onchange='myFunction()', id='selections'),
   form.Button("Submit") 
)