后台代码:
表单里面可以做输入的校验,还可以自己写校验函数,格式要求是固定的
def validate_(属性名)(self,field):
form.py
#表单注册Registration
class RegistrationForm(Form):
###render_kw={}里面保存默认的提示
email = StringField('Email',validators=[Required(),Length(1,64),Email()],render_kw={"placeholder":"请输入邮箱"})
username = StringField('用户名',validators=[Required(),Length(1,64),Regexp('^[A-Za-z][A-Za-z0-9_.]*$',\
0,'用户名必须是字母开头,字母数字结合')],render_kw={"placeholder":"请输入用户名"})
password = PasswordField('密码',validators=[Required(),EqualTo('password2',message='两次密码必须一致')],render_kw={"placeholder":"两次密码必须一致"})
password2 = PasswordField('确认密码',validators=[Required()],render_kw={"placeholder":"两次密码必须一致"})
submit = SubmitField('注册')
def validate_email(self,field):
if User.query.filter_by(email=field.data).first():
raise ValidationError('Email 已注册过.')
def validate_username(self,field):
if User.query.filter_by(username=field.data).first():
raise ValidationError('用户名已存在.')
views.py
@auth.route('/register',methods=['GET','POST'])
def register():
form = RegistrationForm()
if form.validate_on_submit() and form.validate():
user = User(email=form.email.data,username=form.username.data,password=form.password.data)
db.session.add(user)
db.session.commit()
token = user.generate_confirmation_token()
send_email(user.email,'确认你的账户','auth/email/confirm',user,token)
flash('账号验证已发送邮箱!')
return redirect(url_for('auth.login'))
return render_template('auth/register.html',form=form)
前端代码:
有两种快捷的渲染方式
简体快速版(好用推荐!)
<div class="form-wrap">
{{ wtf.quick_form(form) }}
</div>
一个一个生成版
<form class="form" method="POST">
{{ form.hidden_tag() }}
{{ form.email.label }}{{ form.email() }}
<!-- 此处省略其他具体的属性 -->
{{ form.submit() }}
</form>