使用WTForms渲染模板


1、index.html

<form action="" method="post">
  <table>
    <tbody>
    <tr>
      <td>{{form.username.label}}</td>
      <td>{{ form.username }}</td>
    </tr>
    <tr>
      <td>{{ form.password.label }}</td>
      <td>{{ form.password }}</td>
    </tr>
    <tr>
      <td>{{ form.repassword.label }}</td>
      <td>{{ form.repassword }}</td>
    </tr>
    <tr>
      <td></td>
      <td>{{ form.reg }}</td>
    </tr>
    </tbody>
  </table>
</form>
{% for error in form.username.errors %}
  <p>{{ error }}</p>
{% endfor %}
{% for error in form.password.errors %}
  <p>{{ error }}</p>
{% endfor %}
{% for error in form.repassword.errors %}
  <p>{{ error }}</p>
{% endfor %}

2、app.py

from flask import Flask, render_template, request
from wtforms import Form, StringField, PasswordField, SubmitField
from wtforms.validators import Length, EqualTo

class RegForm(Form):
    username = StringField('用户名:', validators=[
        Length(min=6, max=12, message='用户名需要输入6到12个字符')
    ])
    password = PasswordField('密码:', validators=[
        Length(min=6, max=12, message='密码需要输入6到12个字符')
    ])
    repassword = PasswordField('重复密码:', validators=[
        EqualTo('password', message='两次输入的密码需要相同')
    ])
    reg = SubmitField('立即注册')

app = Flask(__name__)

@app.route('/', methods=['GET', 'POST'])
def index():
    form = RegForm(request.form)
    if request.method == 'GET':
        return render_template('index.html', form=form)
    else:
        if form.validate():
            return '注册成功'
        else:
            return render_template('index.html', form=form)

if __name__ == '__main__':
    app.run()

results matching ""

    No results matching ""