《Flask web开发》笔记3:Web表单
一. web 表单实现功能:登录界面、用户注册、信息填写等等一系列操作;
二. 实现步骤:
1.建立表单类,在Flask—web中,web表单里的每一项(用户名、密码、提交按钮等等)对应在表单类变量里都是可以找到,我们需要import ,并且可以添加验证函数(实现字数要求等功能)
一个简单的表单类:
#这里只是展示表单类如何用的,代码片段 from flask_wtf import Form from wtforms import StringField,SubmitField from wtforms.validators import DataRequired class Login(Form): user = StringField('Username', validators=[DataRequired()]) password = StringField('Password', validators=[DataRequired()])
submit = SubmitField('submit')
2.HTML渲染,将表单打印出来咯,不然用户输哪里?
login.HTML:
<form method="POST"> {{ form.hidden_tag() }} {{ form.user.label }} {{ form.user() }} {{ form.password.label }} {{ form.password() }} {{ form.submit() }} </form>
3.回来做个将.py完善一下,运行一下,就Ok了
# coding: utf-8
from flask_wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
from flask import Flask, render_template
class Login(Form):
user = StringField('Username', validators=[DataRequired()])
password = StringField('Password', validators[DataRequired()])
submit = SubmitField('submit')
app = Flask(__name__)
@app.route('/login', methods=('GET', 'POST')) #除了写在HTML的GET,我们还要有提交数据后的请求POST
def login():
form = Login()
if form.validate_on_submit(): #如果提交之后的动作
return ‘login test’
return render_template('login.html', form=form)
if __name__ == '__main__':
app.run(debug = True)
分割线
——————————————————————————————————————————————————————————————————————————————————
拓展一:
渲染的HTML想用Bootstrap的样式来显示,直接上代码:
index.huml:
{% extends "bootstrap/base.html" %} {% import "bootstrap/wtf.html" as wtf %} #注意语法 {% block title %}TTTTT{% endblock %} {% block content %} <div class="container"> <div class="page-header"> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1> </div> </div> {{ wtf.quick_form(form) }} #用在这里!! {% endblock %}
碰到一个问题,书里的例子是{% block page_content %},显示不出来,我找了bootstrap的base.html却也没有发现,不知打是Flask_bootstrap版本的问题还是。。。。
login.py:
# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8') #网上找的方法,错误128 一股脑放上去就没错
from flask import Flask, render_template,url_for,session,redirect,flash # 加了会话、重定向、flash显示
from flask_bootstrap import Bootstrap
from flask_wtf import Form
from wtforms import StringField, SubmitField
from wtforms.validators import Required
class NameForm(Form):
name = StringField('What is your name?', validators=[Required()])
submit= SubmitField('Submit')
app = Flask(__name__)
bootstrap = Bootstrap(app)
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit:
oldname = session.get('name') #1.sesion理解成临时会话空间,存放一次数据,更新后被替代;
#2. session.get('name') 等效于 session['name'],前者如果为空能返回None,后者不行
if oldname is not None and oldname != form.name.data :
flash('换名字啦?不好听!') #flash想用必须先Html渲染,我这里的HTML渲染加在基类里
pass
session['name']= form.name.data
#return redirect(url_for('index'))#1
#return redirect('/') #2 1和2等效,2指定了路由,路由改了值也得改,1随着路由动态调整,可以不用改
pass
return render_template('index.html', form=form, name=session.get('name'))
pass
遗留问题:重定向,网页打开是这样: