标签:提示 contain 表单验证 images key .com pre ref ima
参考文章
第11集
#Sample.py
# coding:utf-8 from flask import Flask,render_template,request from flask_bootstrap import Bootstrap app = Flask(__name__) Bootstrap(app) app.config.from_pyfile(‘config‘) #新建一个config的配置文件 @app.route(‘/login‘,methods=[‘POST‘,‘GET‘]) def login(): from forms import LoginForm form = LoginForm() return render_template(‘login.html‘,title=u‘登录‘,form=form) if __name__ == ‘__main__‘: app.run(debug=True)
#login.html
{% extends ‘home.html‘ %} {% block content %} <div class="page-header"> <div class="container"> <h1>{{ title }}</h1> </div> </div> <div class="container"> <form method="POST"> {{ form.username.label }} {{ form.username() }} {{ form.password.label }} {{ form.password() }} {{ form.submit() }} </form> </div> {% endblock %}
#forms.py
#coding:utf-8 from flask.ext.wtf import Form from wtforms import StringField,PasswordField,SubmitField from wtforms.validators import DataRequired class LoginForm(Form): username = StringField(label=u‘用户名‘,validators=[DataRequired()]) password = PasswordField(label=u‘密码‘,validators=[DataRequired()]) submit = SubmitField(label=u‘提交‘)
#homt.html
{% extends ‘bootstrap/base.html‘ %} {% import ‘_macro.html‘ as ui %} {% block title %}{{ title }}{% endblock %} {% block head %} {{ super() }} {% include ‘includes/_head.html‘ %} {% endblock %} {% block styles %} {{ super() }} <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootswatch/3.3.7/darkly/bootstrap.min.css"> {% endblock %}
#config
防止CSRF
SECRET_KEY=‘hard to guess string‘
效果如图
这里我们可能会觉得这个表单设计的很丑
前面我们学了,引用bootstrap样式,所以也可以将这个表单直接引用,方便快捷
只要改动#login.html的代码(红色代码)
{% extends ‘home.html‘ %} {% import ‘bootstrap/wtf.html‘ as wtf %} {% block content %} <div class="page-header"> <div class="container"> <h1>{{ title }}</h1> </div> </div> <div class="container"> <form method="POST"> {{ wtf.quick_form(form) }} </form> </div> {% endblock %}
效果好了很多
如果我们想在登录后,提示一下‘登录成功’的信息条,怎么设置呢,这里要从flask导入flash(添加到上面代码)
from flask import flash
然后再视图函数下填写(红色代码)
@app.route(‘/login‘,methods=[‘POST‘,‘GET‘]) def login(): from forms import LoginForm form = LoginForm() flash(u‘登陆成功‘) return render_template(‘login.html‘,title=u‘登录‘,form=form)
最后在#login.html中增加代码(红色代码)
{% extends ‘home.html‘ %} {% import ‘bootstrap/wtf.html‘ as wtf %} {% block content %} <div class="page-header"> <div class="container"> <h1>{{ title }}</h1> </div> </div> <div class="container"> {% for message in get_flashed_messages() %} <div class="alert-info">{{ message }}</div> {% endfor %} <form method="POST"> {{ wtf.quick_form(form) }} </form> </div> {% endblock %}
最后效果如图
标签:提示 contain 表单验证 images key .com pre ref ima
原文地址:http://www.cnblogs.com/wongbingming/p/6821175.html