1. 程式人生 > >Flask之WTfroms元件

Flask之WTfroms元件

一、WTfroms簡介

WTForms外掛是類似於django的form元件的外掛,可以幫我們寫標籤,校驗資料等。

二、安裝與使用

安裝:

pip install WTForms

使用:

from wtforms import Form
from wtforms.fields import simple, core
from wtforms import validators

class RegForm(Form):

    username = simple.StringField(
        label="使用者名稱",
        validators
=[ validators.DataRequired(message="資料不能為空!"), validators.length(min=4, max=6, message="使用者名稱不能少於4位且不能大於6位") ], render_kw={"class": "form-control", "pp": "88"} ) password = simple.PasswordField( label="密碼", validators=[ validators.DataRequired(message
="密碼不能為空!"), validators.length(min=6, max=16, message="密碼不能少於6位且不能大於6位"), validators.Regexp(regex="\d+", message="密碼必須是數字") ], render_kw={"class": "form-control", "pp": "88"} ) re_password = simple.PasswordField( label="確認密碼", validators
=[ validators.EqualTo(fieldname="password", message="兩次密碼不一致") ], render_kw={"class": "form-control"} ) gender = core.RadioField( label="性別", validators=[ validators.DataRequired(message="請先選擇一個性別!") ], choices=((1, ""), (2, "")), coerce=int, # default=1, ) hobby = core.SelectMultipleField( label="愛好", choices=((1, "遊戲"), (2, "妹子"), (3, "漢子")), coerce=int, default=[1, 2], render_kw={"class": "form-control"} ) @app.route("/register", methods=("GET", "POST")) def reg(): form_obj = RegForm() if request.method == "POST": print(request.form) form_obj = RegForm(request.form) if form_obj.validate(): ers = request.form.to_dict() print(ers) print(form_obj.data) return "註冊成功" return render_template("reg.html", form_obj=form_obj) if __name__ == '__main__': app.run(debug=True)

前端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <div class="row">
        <div class="col-md-4 col-md-offset-4">
            <form action="" method="post" novalidate>
                {% for field in form_obj %}
                    <div class="form-group">
                        {{ field.label }}
                        {{ field }}
                        {{ field.errors.0 }}
                    </div>
                {% endfor %}
                <div>
                    <button class="btn btn-primary btn-lg btn-block">註冊</button>
                </div>
            </form>
        </div>
    </div>
</div>

</body>
</html>