1.概述
渲染模板是WTForms的第二个作用,具体功能技术通过python代码生成html代码——模板渲染
2.使用方式
- 表单对象.属性.label
- 获取带有label标签的属性
- 表单对象.属性.label.text
- 获取属性名
- 表单对象.属性()
- 获取对应的表单元素
3.代码展示
3.1wtforms创建类
from wtforms_tornado import Form
from wtforms.fields import IntegerField, StringField, HiddenField
from wtforms.validators import DataRequired, Length
# 创建一个表单类
class UserForm(Form):
# 定义字段:注意 验证字段的名字一定要和前端传递来的名字保持一致
# 编写规则
id = HiddenField('ID') # 隐藏字段
username = StringField('用户名',validators=(DataRequired(message='请填写用户名'),Length(min=3,max=10,message='请输入3-10位的用户名')))
nick_name = StringField('昵称')
email = StringField('邮箱')
password = StringField('密码')
phone = StringField('电话')
language = StringField('语言')
3.2 Tornado返回
from tornado.web import Application, RequestHandler, URLSpec
from tornado.ioloop import IOLoop
from wtforms35 import UserForm
class IndexHandle(RequestHandler):
def get(self):
uf = UserForm()
self.render('personal35.html',uf=uf)
if __name__ == '__main__':
import os
# 获取绝对路径
base_path = os.path.abspath(os.path.dirname(__file__))
# 设置应用参数
settings = {
'template_path':os.path.join(base_path, 'templates'),
'static_path': os.path.join(base_path, 'static'),
'static_url_prefix': '/static/',
'debug': True
}
# 创建Tornado应用
app = Application([
URLSpec('/',IndexHandle)
], **settings)
# 设置监听端口号
app.listen(8000)
IOLoop.current().start()
3.3wtforms的使用
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<!-- Title Page-->
<title>个人信息</title>
<!-- Bootstrap CSS-->
<link href="{{static_url('css/bootstrap.min.css')}}" rel="stylesheet" media="all">
<!-- Main CSS-->
<link href="{{static_url('css/theme.css')}}" rel="stylesheet" media="all">
</head>
<body class="animsition">
<div class="page-wrapper">
<div class="page-content--bge5">
<div class="container">
<div class="login-wrap">
<div class="login-content">
<div class="login-logo">
<a href="#">
<img src="{{static_url('img/logo2.png')}}" alt="CoolAdmin">
</a>
</div>
<div class="login-form">
<form action="/" method="post">
{% autoescape None %} <!-- 停用解析html,禁止打印出来html源码 -->
{% for f in uf %}
{% if f.label.text == 'ID' %}
<div class="form-group">
{{ f(class_="au-input au-input--full",placeholder=f.label.text) }}
</div>
{% else %}
<div class="form-group">
{{ f.label }}
{{ f(class_="au-input au-input--full",placeholder=f.label.text) }}
</div>
{% end %}
{% end %}
<div class="form-group">
<label>用户名</label>
<input class="au-input au-input--full" type="text" name="username" placeholder="Username">
</div>
<button class="au-btn au-btn--block au-btn--green m-b-20" type="submit">确 认</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<!-- end document-->