[Flask]經過render_form快捷渲染表單

依賴:css

Bootstrap-Flaskhtml

實例化方式與flask_bootstrap相同.sql

 

關於render_form():flask

Bootstrap-Flask內置了兩個用於渲染WTForms表單類的宏,render_form()宏會自動渲染錯誤消息,渲染表單的驗證狀態樣式.bootstrap

Bootstrap-Flask提供的表單渲染宏經過其內置的bootstrap/form.html模板導入,render_form()宏,使用起來很是簡單.使用一行代碼就能夠渲染整個表單,並且會自動幫咱們渲染CSRF令牌字段form.csrf_token.app

post.htmlpost

<!DOCTYPE html> {%extends 'base.html'%} {%from 'bootstrap/form.html' import render_form%} <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> {{bootstrap.load_css()}} </head> <body> {%block content%} <div class="hello-form"> <--{{form.csrf_token}}--> #使用render_form就不用本身寫這一句了
{{render_form(form)}} </div> {%endblock%} {{bootstrap.load_js()}} </body> </html>

render_form()會自動爲你建立一個<form>標籤,而後在標籤內依次渲染包括CSRF令牌在內的全部字段.除了渲染表單字段,它還會根據表單的驗證狀態來渲染表單狀態和錯誤消息.ui

base.htmlurl

<!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:24x" 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">&uarr;</a></p> {%endblock%} </footer> </main> </body> {{bootstrap.load_js()}} </html>

app.pyspa

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__) 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 = SQLAlchemy(app) bootstrap=Bootstrap(app) 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('提交') @app.route('/post/<int:post_id>',methods=['GET','POST']) def show_post(post_id): form = PostForm() return render_template('post.html',form=form)

效果:

 

 

 

 下拉列表:

相關文章
相關標籤/搜索