1.开发环境需要安装插件,flask-wtf插件.
pip install flask-wtf
2.login.html
<head>
<meta charset="utf-8">
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/flatly/bootstrap.min.css">
head>
{% block navbar %}
{{ nav.top.render() }}
{% endblock %}
<body>
{% import 'bootstrap/wtf.html' as wtf %}
<div align="center" >
<form class="form" method="POST">
{{ form.hidden_tag() }}
{{ wtf.form_field(form.email) }}
{{ wtf.form_field(form.password) }}
{{ wtf.form_field(form.submit) }}
form>
div>
body>
3.在视图中增加,表单提交操作。引用的python文件在文章最后,检查一遍。
@app.route('/login', methods=['GET', 'POST'])
def login():
form = forms.LoginForm()
if form.validate_on_submit():
return "ok"
return render_template('login.html', form=form)
3.创建forms.py生成表单
#!flask/bin/env python
#coding:utf-8
from flask_wtf import FlaskForm
from wtforms.validators import DataRequired, Length, Email
from wtforms import *
class LoginForm(FlaskForm):
email = StringField(u'邮箱', validators=[
DataRequired(message= u'邮箱不能为空'), Length(1, 64),
Email(message= u'请输入有效的邮箱地址,比如:[email protected]')])
password = PasswordField(u'密码',
validators=[DataRequired(message= u'密码不能为空')])
submit = SubmitField(u'登录')
4.创建config.py 作为配置文件
# coding:utf-8
CSRF_ENABLED = True
SECRET_KEY = 'bstc1234'
DEBUG = True
ITEMS_PER_PAGE = 10
#启动CSRF保护
#其中SECRET_KEY用来建立加密的令牌,用于验证Form表单提交
5视图文件别忘了增加import 的python文件,对比下面的检查一遍。
# coding:utf-8
from flask import Flask,render_template,request,url_for
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
import forms
import config