[Flask]通过render_form快捷渲染表单

依赖:

Bootstrap-Flask

实例化方式与flask_bootstrap相同.

 

关于render_form():

Bootstrap-Flask内置了两个用于渲染WTForms表单类的宏,render_form()宏会自动渲染错误消息,渲染表单的验证状态样式.

Bootstrap-Flask提供的表单渲染宏通过其内置的bootstrap/form.html模板导入,render_form()宏,使用起来非常简单.使用一行代码就可以渲染整个表单,而且会自动帮我们渲染CSRF令牌字段form.csrf_token.

post.html

<!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令牌在内的所有字段.除了渲染表单字段,它还会根据表单的验证状态来渲染表单状态和错误消息.

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: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.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__)

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)

效果:

 

 

 

 下拉列表:

 

 

 

 

posted @ 2019-11-20 11:12  wangju003  阅读(2408)  评论(0编辑  收藏  举报