from datetime import datetimefrom app import db# 会员class User(db.Model): __tablename__ = "user" id = db.Column(db.Integer, primary_key=True) # 编号 name = db.Column(db.String(100), unique=True) # 昵称 pwd = db.Column(db.String(100)) # 密码 email = db.Column(db.String(100), unique=True) # 邮箱 phone = db.Column(db.String(11), unique=True) # 手机号码 info = db.Column(db.Text) # 个性简介 face = db.Column(db.String(255), unique=True) # 头像 addtime = db.Column(db.DateTime, index=True, default=datetime.now) # 注册时间 uuid = db.Column(db.String(255), unique=True) # 唯一标志符 userlogs = db.relationship('Userlog', backref='user') # 会员日志外键关系关联 comments = db.relationship('Comment', backref='user') # 评论外键关系关联 moviecols = db.relationship('Moviecol', backref='user') # 收藏外键关系关联 def __repr__(self): return "" % self.name # 检查密码匹配 def check_pwd(self, pwd): from werkzeug.security import check_password_hash return check_password_hash(self.pwd, pwd)
第一步:定制forms表单
# -*- coding: utf-8 -*-# @Author: Laifrom flask_wtf import FlaskFormfrom wtforms import StringField, PasswordField, SubmitFieldfrom wtforms.validators import DataRequired, EqualToclass RegistForm(FlaskForm): name = StringField( label="昵称", description="昵称", validators=[ DataRequired("请输入昵称"), ], render_kw={ "class": "form-control input-lg", "placeholder": "昵称", } ) email = StringField( label="邮件", description="邮件", validators=[ DataRequired("请输入邮件"), ], render_kw={ "class": "form-control input-lg", "placeholder": "邮件", } ) phone = StringField( label="电话", description="电话", validators=[ DataRequired("请输入电话"), ], render_kw={ "class": "form-control input-lg", "placeholder": "电话", } ) pwd = PasswordField( label="密码", description="密码", validators=[ DataRequired("请输入密码"), ], render_kw={ "class": "form-control input-lg", "placeholder": "密码", } ) repwd = PasswordField( label="", description="", validators=[ DataRequired("请再次输入密码"), EqualTo("pwd", message="前后密码不一致"), ], render_kw={ "class": "form-control input-lg", "placeholder": "再次输入密码", } ) submit = SubmitField( label="注册", render_kw={ "class": "btn btn-lg btn-success btn-block", } ) def validate_phone(self, field): phone = field.data rex = "1[358]\d{9}" if not re.findall(rex, phone): raise ValidationError("手机格式不正确")
第二步:改造html模板
第三步:接收post请求数据存入数据库
from . import homefrom flask import render_template, redirect, url_for, flashfrom .forms import RegistFormfrom werkzeug.security import generate_password_hashfrom app.models import Userfrom app import db@home.route("/regist/", methods=["GET", "POST"])def regist(): form = RegistForm() if form.validate_on_submit(): data = form.data name = data.get("name") email = data.get("email") phone = data.get("phone") pwd = generate_password_hash(data.get("pwd")) user = User( name=name, email=email, phone=phone, pwd=pwd, ) db.session.add(user) db.session.commit() flash("注册成功", "ok") return redirect(url_for('home.login')) return render_template("home/regist.html", form=form)