[Flask] 关于render_form 快速渲染表单
内容简介
当我们在使用route的methods=['GET','POST']时候,通常使用语句 if flask.request.method方法 来处理request。但是 flask_bootstrap 方法,可以非常快速的处理这个request。
具体来说
对于bootstrap_flask,从内置的 form.html 中导入 render_form() 会自动根据定义好的 表单类 渲染。
目录结构
|- post.html
|- base.html
|- app.py
post.html
<!DOCTYPE html>
<!-- extends + 模板 = 引用模板 -->
{%extends 'base.html'%}
<!-- 从form.html中找到render_form() -->
{%from 'bootstrap/form.html' import render_form%}
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<!-- 加载css -->
{{bootstrap.load_css()}}
</head>
<body>
{%block content%}
<div class="hello-form">
{{render_form(form)}} <!-- 一句导入+创建<form>+渲染 -->
</div>
{% endblock %}
{{bootstrap.load_css()}}
</body>
</html>
base.html
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no">
<title>{%block tile %}Say hello !{%endblock%}</title>
{{bootstrap.load_css()}}
</head>
<body>
<main class="container">
<header>
<h1 class="text-center display-4">
<small style="font: size 24px;" class="text-muted">Hello World</small>
</h1>
</header>
{%block content%}{%endblock%}
<footer class="text-center">
{%block footer%}
<p>
<a id="bottom" href="#" title="Go Top">
↑
</a>
</p>
{%endblock%}
</footer>
</main>
</body>
</html>
app.py
from flask import Flask, render_template, url_for, flash
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SelectField,SubmitField
from wtforms.validators import DataRequired
from flask_bootstrap import Bootstrap
import os
basedir = os.path.abspath(os.path.dirname(__file__))
app = Flask(__name__)
# ----- 配置db -----
app.config['SQLALCHEMY_DATABASE_URI']='sqlite:///'+os.path.join(basedir,'data.sqlite')
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
app.config['SECRET_KEY']='secret key'
# ----- 加载db和bootstrap -----
db = SQLAlchemy(app)
bootstrap=Bootstrap(app)
# ----- 定义db -----
class Post(db.Model):
id = db.Column(db.Integer,primary_key=True)
title = db.Column(db.String(255))
category = db.Column(db.String(64))
def __repr__(self):
return '<Post.>%s'%self.title
# ----- 定义表单类 -----
class PostForm(FlaskForm):
title = StringField('姓名',validators=[DataRequired()])
category=SelectField('维护状态',choices=[('未维护','未维护'),('维护中','维护中'),('已维护','已维护')])
submit = SubmitField('SUBMIT')
new_submit = SubmitField('new_submit')
@app.route('/',methods=['GET','POST'])
def show_post():
form = PostForm()
return render_template('post.html',form=form)