美文网首页
Flask-FlaskWTF表单扩展(二),登陆后跳转

Flask-FlaskWTF表单扩展(二),登陆后跳转

作者: 测试探索 | 来源:发表于2020-09-25 07:04 被阅读0次

    本代码,为上一代码扩展,增加了登陆后跳转的功能

    from flask import Flask,render_template,redirect,url_for,session
    from flask_wtf import FlaskForm
    from wtforms import StringField,PasswordField,SubmitField
    from wtforms.validators import DataRequired,EqualTo
    
    app = Flask(__name__)
    
    app.config["SECRET_KEY"] = "asdfewq"
    #定义表单的模型类
    class RegisterForm(FlaskForm):
        """
        自定义的注册表单模型类
        """
        # label为字段说明标签,第二个参数验证器
        # DataRequired 保证数据必须填写,并且不能为空
        user_name = StringField(label="用户名",validators=[DataRequired("用户名不能为空")])
        password = PasswordField(label="密码",validators=[DataRequired("密码不能为空")])
        password2 = PasswordField(label="确认密码",validators=[DataRequired("确认密码不能为空"),
                                                           EqualTo("password","两次密码不一致")])
        submit = SubmitField(label="提交")
    
    
    @app.route("/register",methods=["GET","POST"])
    def register():
        # 创建表单对象,如果是post请求,前端发送数据
        # flask会把数据在构造form对象的时候,存放到对象中
        form = RegisterForm()
        # 判断form中的数据是否合理
        if form.validate_on_submit():
        #     表示验证合格
        #     提取数据
            uname = form.user_name.data
            pwd = form.password.data
            pwd2 = form.password2.data
            print(uname,pwd,pwd2)
            session["user_name"] = uname
            return redirect(url_for("index"))
    
        # 如果form中的数据,完全满足所有的验证器,则返回真,否则返回假
        return render_template("register.html",form=form)
    
    
    @app.route("/index")
    def index():
        user_name = session.get("user_name","")
    
        return "Hello %s" % user_name
    
    if __name__ == '__main__':
        app.run(debug=True)
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <form method="post">
            #token很重要
            {{ form.csrf_token }}
            {{ form.user_name.label }}
            <p>{{ form.user_name }}</p>
            {% for msg in  form.user_name.errors %}
            <p>{{ msg }}</p>
            {% endfor %}
    
            {{ form.password.label }}
            <p>{{ form.password }}</p>
            {% for msg in  form.password.errors %}
            <p>{{ msg }}</p>
            {% endfor %}
    
            {{ form.password2.label }}
            <p>{{ form.password2 }}</p>
            {% for msg in  form.password2.errors %}
            <p>{{ msg }}</p>
            {% endfor %}
    
            {{ form.submit }}
    
        </form>
    
    </body>
    </html>
    

    相关文章

      网友评论

          本文标题:Flask-FlaskWTF表单扩展(二),登陆后跳转

          本文链接:https://www.haomeiwen.com/subject/xzyxuktx.html