原文: http://106.13.73.98/__/120/
下载:pip install WTForms
第一步 Flask脚本:
from flask import Flask, request, render_template, views
from wtforms import Form, validators
from wtforms.fields import simple, core
app = Flask(__name__)
# --------------------------------------------------------------------------
class RegForm(Form):
nickname = simple.StringField(
label="昵称",
validators=[
validators.DataRequired(message="昵称不可为空")
],
render_kw={'class': 'my_username'} # 自定义扩展属性
)
password = simple.PasswordField(
label="密码",
validators=[
validators.DataRequired(message="密码不可为空"),
# validators.Length(min=3, max=9, message="密码最小3位,最大9位"),
validators.Length(min=6, max=6, message="密码必须为6位"),
# 支持正则的匹配:
validators.Regexp(regex='\d+', message="密码必须为纯数字"),
]
)
repassword = simple.PasswordField(
label="校验密码",
validators=[
validators.EqualTo(fieldname='password', message="密码不一致")
# 这里将获取password属性的值,并与本属性的值做比较,如果不一致则阻拦
]
)
# 邮箱
email = simple.StringField(
label="邮箱",
validators=[
validators.Email(message="邮箱格式错误"),
]
)
# 单选纽扣??
gender = core.RadioField(
label="性别",
coerce=int,
choices=((1, "男"), (2, "女"), (3, "密")),
default=1, # 性别默认为男
)
# 多选框
hobby = core.SelectMultipleField(
label="爱好",
coerce=int,
choices=((1, 'Python'), (2, 'Flask'), (3, 'Django'), (4, 'Java')),
default=(1, 2, 3) # 默认选中
)
# 提交按钮
submit = simple.SubmitField(
label="提交"
)
# --------------------------------------------------------------------------
class Reg(views.MethodView):
def get(self):
rf = RegForm() # ??
return render_template('reg.html', rf=rf)
def post(self):
# 校验数据
rf = RegForm(request.form)
# 判断是否校验成功
if rf.validate():
# 数据存放在rf.data中
userinfo = rf.data
return 'Registered successfully.'
return render_template('reg.html', rf=rf)
# 注册CBV的路由,一个CBV可以有多条路由
app.add_url_rule('/reg', view_func=Reg.as_view('reg'))
app.run(debug=True)
第二步 模版文件:
<form method="post">
{% for field in rf %}
<div>{{ field.label }}{{ field }}{{ field.errors.0 }}</div>
<hr>
{% endfor %}
</form>
第四步 浏览器:
原文: http://106.13.73.98/__/120/
原文地址:https://www.cnblogs.com/gqy02/p/11322802.html
时间: 2024-11-06 17:29:21