python flask web开发实战 表单 form flask-wtf

2019-07-05 11:14:51 浏览数 (1)

hello.py 中CSRF

app = Flask(name) app.config['SECRET_KEY'] = 'hard to guess string' 1、

表单,hello.py

from flask.ext.wtf import Form from wtforms import StringField,SubmitField from wtforms.valiadators import Required

class NameForm(Form): name=StringField('What is your name?',validators=[Required()]) submit=SubmitField('Submit')


html 基本不适用

<form method="POST"> {{ form.hidden_tag() }} {{ form.name.label }} {{ form.name(id='my-text-field') }} {{ form.submit() }} </form>


or #html 使用bootstrap渲染表单,wtf.quick_form(form) {% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf %} {% block title %}Flasky{% endblock %} {% block page_content %} <div class="page-header"> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1> </div> {{ wtf.quick_form(form) }} {% endblock %}


hello.py @app.route('/',methods=['GET','POST']) form.name.data

@app.route('/', methods=['GET', 'POST']) def index(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=name)


2、

支持

StringField TextAreaField PasswordField HiddenField DateField DateTimeField IntegerField DecimalField FloatField BooleanField 复选框 RadioField SelectField SelectMultipleField FileField 文件上传 SubmitField FormField FieldList 3、

验证

Email EqualTo IPAddress Length NumberRange Optional Required 确保有数据 Regexp 正则 URL AnyOf 在值内 NoneOf 不在 4、 ###########记住用户是否登录, from flask import Flask, render_template, session, redirect, url_for @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'))

0 人点赞