• 怎样使用表单 forms
    • 问题:
    • 解决:

    怎样使用表单 forms

    问题:

    怎样使用表单 forms

    解决:

    ‘web.form’模块提供支持创建,校验和显示表单。该模块包含一个’Form’类和各种输入框类如’Textbox’,’Password’等等。

    当’form.validates()’调用时,可以针对每个输入检测的哪个是有效的,并取得校验理由列表。

    ‘Form’类同样可以使用完整输入附加的关键字参数’validators’来校验表单。

    这里是一个新用户注册的表单的示例:

    1. import web
    2. from web import form
    3. render = web.template.render('templates') # your templates
    4. vpass = form.regexp(r".{3,20}$", 'must be between 3 and 20 characters')
    5. vemail = form.regexp(r".*@.*", "must be a valid email address")
    6. register_form = form.Form(
    7. form.Textbox("username", description="Username"),
    8. form.Textbox("email", vemail, description="E-Mail"),
    9. form.Password("password", vpass, description="Password"),
    10. form.Password("password2", description="Repeat password"),
    11. form.Button("submit", type="submit", description="Register"),
    12. validators = [
    13. form.Validator("Passwords did't match", lambda i: i.password == i.password2)]
    14. )
    15. class register:
    16. def GET(self):
    17. # do $:f.render() in the template
    18. f = register_form()
    19. return render.register(f)
    20. def POST(self):
    21. f = register_form()
    22. if not f.validates():
    23. return render.register(f)
    24. else:
    25. # do whatever is required for registration

    然后注册的模板应该像是这样:

    1. $def with(form)
    2. <h1>Register</h1>
    3. <form method="POST">
    4. $:form.render()
    5. </form>