** web form view and rendering functions **
1、安装Flask-WTF
pip install flask-wtf
Example:
import module corresponding
NameForm form has a text field called name and a submit button to submit the name
StringField class represents the attribute type = "text" of the <input> function
SubmitField class represents the attribute type = "submit" in <input> element
first constructor parameter field of the reference used in the form rendering into HTML
verification function the Required () field is not empty, filed ensure
Example:
1, the directory structure
2, modified in view function hello.py so that the form can be processed
from flask import Flask,request,make_response,redirect,render_template from flask_bootstrap import Bootstrap from flask_wtf import Form from wtforms import StringField,SubmitField from wtforms.validators import Required app = Flask(__name__) app.config["SECRET_KEY"] = "123456" bootstrap = Bootstrap(app) class NameForm(Form): name = StringField('what is your name?', validators=[Required()]) submit = SubmitField('Submit') @app.route('/', methods=['GET', 'POST']) def index(): name = None form = NameForm() if form.validate_on_submit(): name = form.name.data form.name.data = '' return render_template('index.html', form=form, name=name) @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500 @app.route('/user/<name>') def user(name): return render_template('user.html', name=name) @app.route('/user/<id>') def get_user(id): user = load_user(id) if not user: abort(404) return '<h1>Hello, %s</h1>' % user.name if __name__ == '__main__': bootstrap.run()
3, using templates / index.html in Flask-WTF and Flask-Bootstrap render the form
template is now divided into two parts, the first part is a header page, displays a welcome message
Jinja2 conditional statements in the format of {% if condition%}. .. {% else%} ... { % endif%}
If the condition is True, then rendering value between the if and else instructions. If the condition evaluates to False, and the rendering values between endif else
{% extends "base.html" %} {% import "bootstrap/wtf.html" as wtf%} {% block title %}Flasky{% endblock %} {% block page_content %} <div class="page-header"> <h1>Hello, {% if name %}{{ name }}{% else %}Stranger{% endif %}</h1> </div> {{ wtf.quick_form(form)}} {% endblock %}
4、base.html
{% extends "bootstrap/base.html" %} {% block title %}Flasky{% endblock %} {% block navbar %} <div class="navbar navbar-inverse" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="/">Flask</a> </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="/">Home</a></li> </ul> </div> </div> </div> {% endblock %} {% block content %} <div class="container"> <div class="page-header"> {% block page_content %}{% endblock %} </div> </div> {% endblock %}
5 results
When you submit an empty form, Required () function to verify the error captured
** ** redirection and user sessions
When submitting the names, then refresh the page, there will be alarm
One way to handle this is to ensure that the alarm is get the last commit request, there will be the problem is that the program is processing a POST request, obtain form.name.data use the name entered by the user, but once the request is over, the data will be lost a. Therefore, when the redirect, you need to save the entered name, you can use the session
1, hello.py modify, redirect the user sessions, and
Recommended url_for () generates a URL, because the function uses URL mapping generated URL, and the URL to ensure that the definition of routing-compatible, and the revised routing name can still use
Use session.get ( 'name') corresponding to the key acquisition dictionary abnormality value to avoid the key is not found, the key for does not exist, GET () returns the default value of None
from flask import Flask,request,make_response,redirect,render_template,session,url_for @app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form=form, name=session.get('name'))
After submitting the name refresh again, no alarm information
** flash message **
The request is complete, you can confirm the message, warning or error message telling the user changes state
when a user submits a login form with errors, the server sends back a response to re-render the login form, and displays a message on the form, prompt the user name or password is incorrect
1, modify hello.py, achieve flash
@app.route('/', methods=['GET', 'POST']) def index(): form = NameForm() if form.validate_on_submit(): old_name = session.get('name') if old_name is not None and old_name != form.name.data: flash('Looks like you have changed your name!') session['name'] = form.name.data return redirect(url_for('index')) return render_template('index.html', form = form, name = session.get('name'))
2, modify the templates / base.html, rendering Flash news
Flask put get_flashed_messages () function to open a template, to obtain and render the message
Using a loop in the template is because before each flash cycle request call () function generates a message,
it may have a plurality of display messages queued. get_flashed_messages () function to get the message in the next transfer
will not return again with, so Flash message is displayed only once, then disappeared
{% block content %} <div class="container"> {% for message in get_flashed_messages() %} <div class="alert alert-warning"> <button type="button" class="close" data-dismiss="alert">×</button> {{ message }} </div> {% endfor %} {% block page_content %}{% endblock %} </div> {% endblock %}
3, when the page is not the same name twice submitted, there will be alarm information