flask_wtf Form 表单类的使用

设置密匙

flask-WTF为了保护表单免受跨站请求伪造的攻击,为了实现CSRF的保护,使用表单类之前,要先设置一个密钥,设置密钥的方式如下:

	app = Flask(__name__)
	app.config['SECRET_KEY'] = 'python flask' # 此处内容可以自定义

定义表单类 -后台

# 导入相应模块
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
# 表单类
class NewForm(Form):
    """docstring for NewForm"""
    # 定义一个文本框  验证函数Required() 验证输入是否为空
    name = StringField('user name', validators=[Required()]) 
    # 定义一个提交按钮
    submit = SubmitField('submit')

定义路由传递表单实例

@app.route('/')
def index():
	return render_template('index.html', form=NewForm())

把表单类渲染成HTML

index.html
	<form method='POST'>
		{{ form.name.label }} : {{ form.name() }}
		<br>
		{{ form.submit() }}
	</form>

猜你喜欢

转载自blog.csdn.net/weixin_42600599/article/details/83785087