初涉flaskWeb表单
程序员文章站
2022-04-22 15:01:45
...
使用前导:pip install flask-wtf
flask的wtf扩展可以渲染一个表单,包含一个文本字段和提交按钮,wtf提供多种HTML标准字段与验证函数
今日实践代码:
- FlaskForm要从flask_wtf导入
- html标准字段与WTForm验证函数可直接从wtforms直接导入
from flask_bootstrap import Bootstrap
from flask import Flask
from flask import render_template
from flask_moment import Moment
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
bootstrap = Bootstrap(app)
moment = Moment(app)
class NameForm(FlaskForm):#继承FlaskForm的类,并形成一个文本填写字段,验证方式,并提交
name = StringField('what is your name?', validators=[DataRequired()])
submit = SubmitField('Submit')
@app.errorhandler(404)
def er404(e):
return render_template('404.html'), 404
@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()#声明一个form类
if form.validate_on_submit():
name = form.name.data
form.name.data = ''#重置文本字段为空
return render_template('index.html', form = form, name=name)
if __name__ == '__main__':
app.run(host='127.0.0.1', port=9999, debug=True)
{% extends 'bootstrap/base.html' %}
{% block title %}Flasky{% endblock %}
{% block head %}
{{ super() }}
<line rel='shortcut icon' href="{{ url_for('static', filename='favicon.ico') }}" type='image/x-icon'>
<line rel='icon' href="{{ url_for('static', filename='favicon.ico') }}" type='image/x-icon'>
{% endblock %}
{% block navbar %}
<div class='navbar navbar-inverse' role='navigation'>
<div class='container'>
<div class='navbar-header'>
<button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'>
<span class='sr-only'>Toggle navigation</span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
<span class='icon-bar'></span>
</button>
<a class='navbar-brand' href='/'>Flasky</a>
</div>
<div class='navbar-collapse collapse'>
<ul class='nav navbar-nav'>
<li><a href="/">Home</a></li>
</ul>
</div>
</div>
</div>
{% endblock %}
{% block content %}
<div class='container'>
{% block page_content %}{% endblock %}
</div>
{% endblock %}
{% block scripts %}
{{ super() }}
{{ moment.include_moment() }}
{% endblock %}
每一个block声明是bootstrap渲染的标志,以endblock结束
{% 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 %}
wtf.quick_form(form):wtf快速渲染的插件
下一篇: php防止sql注入漏洞代码,