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
Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Is HTML easy to learn for beginners?Is HTML easy to learn for beginners?Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is an example of a starting tag in HTML?What is an example of a starting tag in HTML?Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

How to use CSS's Flexbox layout to achieve centering alignment of dotted line segmentation effect in menu?How to use CSS's Flexbox layout to achieve centering alignment of dotted line segmentation effect in menu?Apr 05, 2025 pm 01:24 PM

How to design the dotted line segmentation effect in the menu? When designing menus, it is usually not difficult to align left and right between the dish name and price, but how about the dotted line or point in the middle...

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.