search
HomeWeb Front-endHTML TutorialFlask学习笔记-在Bootstrap框架下Web表单WTF的使用_html/css_WEB-ITnose

表单的处理一般都比较繁琐和枯燥,如果想简单的使用表单就可以使用Flask-WTF插件,同时我们把WTF融合到Bootstrap中这样样式的问题都自动解决了,本篇文章就为您讲解这些内容。

先要注意一点,在使用WTF的时候我们要在程序中设定一下SECRET_KEY,不然会出现"Must provide secret_key to use csrf"错误。

app.config['SECRET_KEY'] = 'xxxx'

Flask-Bootstrap在前面的文章中已经讲过了,不再重复。

后台WTF编码

先看实例:

from flask.ext.wtf import Formfrom wtforms import StringField, SubmitField, SelectFieldfrom wtforms.validators import DataRequiredclass BookForm(Form):    name = StringField('姓名', validators=[DataRequired()])    phone = StringField('电话', validators=[DataRequired()])    photoset = SelectField('套系', choices=[('SET1', '1'), ('SET2', '2')])    submit = SubmitField("预定")    @app.route('/book/', methods=['GET', 'POST'])def book_photo():    name = None    phone = None    photoset = None    booker = BookForm()    if booker.validate_on_submit():        name = booker.name.data        phone = booker.phone.data        photoset = booker.photoset.data    return render_template('book_photo.html', form=booker, name=name, phone=phone, photoset=photoset)

BookForm是我们自己定义的一个Form对象,里面包含了两个文本框和一个下拉选择框,很简单。

class BookForm(Form):    name = StringField('姓名', validators=[DataRequired()])    phone = StringField('电话', validators=[DataRequired()])    photoset = SelectField('套系', choices=[('SET1', '1'), ('SET2', '2')])    submit = SubmitField("预定")

validators是输入检查控制器,有很多种,这里使用的是DataRequired用于必填项的检查,还有字符长度以及输入类型等等好多控制器,需要说明一下在SelectField中不要使用这些不然会报错,这个地方我没有深入研究,暂时就不使用了,哈。

book_photo()是/book/的处理函数,我们初始化了文本框的默认为空,还初始化了BookForm对象,render_template函数指定了页面和form对象。

if booker.validate_on_submit():        name = booker.name.data        phone = booker.phone.data        photoset = booker.photoset.data

这段处理是在表单提交后的接收参数值的处理逻辑,同时还是用

return render_template('book_photo.html', form=booker, name=name, phone=phone, photoset=photoset)

返回了name,phone和photoset值到book_photo.html页面。

下面我们就来看下页面的代码

表单页面

{% extends "base.html" %}{% import "bootstrap/wtf.html" as wtf %}{% block page_content %}    <div class="page-header">        数据:        <p>        {% if name %}            {{ name }}        {% endif %}        <br />        {% if phone %}            {{ phone }}        {% endif %}        <br />        {% if photoset %}            {{ photoset }}        {% endif %}        </p>    </div>    {{ wtf.quick_form(form) }}{% endblock %}

很简单吧,因为我们使用了bootstrap/wtf.html的基模板,很好的跟bootstrap结合起来。

重点是:

{{ wtf.quick_form(form) }}

我们利用wtf.quick_form函数自动生成了表单,非常cool对不对。

    <div class="page-header">        数据:        <p>        {% if name %}            {{ name }}        {% endif %}        <br />        {% if phone %}            {{ phone }}        {% endif %}        <br />        {% if photoset %}            {{ photoset }}        {% endif %}        </p>    </div>

这段是表单提交后显示提交数据的处理,所以我们在一个页面上就搞定了表单的显示和提交后的数据显示。

显示结果

还挺不错的是不是。

高级-重定向会话

我们提交表单后最后一个请求为POST,这样我们在刷新页面的时候会出现重新提交表单,通过重定向会话就可以解决这个问题(这个技巧称“Post/重定向/Get模式”),还有就是可以通过重定向会话实现自定义的跳转等更灵活的控制。

重定向会话我们要利用session机制实现,代码如下:

from flask import Flask, render_template, send_from_directory, session, redirect, url_for@app.route('/book/', methods=['GET', 'POST'])def book_photo():    name = None    phone = None    photoset = None    booker = BookForm()    if booker.validate_on_submit():        session['name'] = booker.name.data        session['phone'] = booker.phone.data        session['photoset'] = booker.photoset.data        return redirect(url_for('book_photo'))    return render_template('book_photo.html', form=booker, name=session.get('name'), phone=session.get('phone'), photoset=session.get('photoset'))

高级-Flash消息

如果需要页面通知用户消息的话,可以使用Flash消息,也很简单,代码如下:

from flask import Flask, render_template, send_from_directory, session, redirect, url_for, flash@app.route('/book/', methods=['GET', 'POST'])def book_photo():    name = None    phone = None    photoset = None    booker = BookForm()    if booker.validate_on_submit():        old_name = session.get('name')        if old_name is not None and old_name != booker.name.data:            flash('您的提交发生变化')        session['name'] = booker.name.data        session['phone'] = booker.phone.data        session['photoset'] = booker.photoset.data        return redirect(url_for('book_photo'))    return render_template('book_photo.html', form=booker, name=session.get('name'), phone=session.get('phone'), photoset=session.get('photoset'))

判断字段值的变化,设置提示信息

        if old_name is not None and old_name != booker.name.data:            flash('您的提交发生变化')

页面上也需要处理:

{% extends "base.html" %}{% import "bootstrap/wtf.html" as wtf %}{% block page_content %}    <div class="page-header">        数据:        <p>        {% if name %}            {{ name }}        {% endif %}        <br />        {% if phone %}            {{ phone }}        {% endif %}        <br />        {% if photoset %}            {{ photoset }}        {% endif %}        </p>    </div>    {% for message in get_flashed_messages() %}    
{{ message }} {% endfor %}
{{ wtf.quick_form(form) }}{% endblock %}

通过for/endfor进行控制,也是使用的bootstrap的样式

{% for message in get_flashed_messages() %}<div class="alert alert-warning">    <button type="button" class="close" data-dismiss="alert">&times;</button>    {{ message }}{% endfor %}

效果如下:

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment