Skip to content
Myr

flashing.rst

This file

Path

docs/patterns/flashing.rst

81 lines · 2.3 KiB

Last changed by

Added WTForms documentation.Armin Ronacherbefore adoptionce18d45

History of this file

Take it

1.. _message-flashing-pattern:23Message Flashing4================56Good applications and user interfaces are all about feedback.  If the user7does not get enough feedback he will probably end up hating the8application.  Flask provides a really simple way to give feedback to a9user with the flashing system.  The flashing system basically makes it10possible to record a message at the end of a request and access it next11request and only next request.  This is usually combined with a layout12template that does this.1314So here a full example::1516    from flask import flash, redirect, url_for, render_template1718    @app.route('/')19    def index():20        return render_template('index.html')2122    @app.route('/login', methods=['GET', 'POST'])23    def login():24        error = None25        if request.method == 'POST':26            if request.form['username'] != 'admin' or \27               request.form['password'] != 'secret':28                error = 'Invalid credentials'29            else:30                flash('You were sucessfully logged in')31                return redirect(url_for('index'))32        return render_template('login.html', error=error)3334And here the ``layout.html`` template which does the magic:3536.. sourcecode:: html+jinja3738   <!doctype html>39   <title>My Application</title>40   {% with messages = get_flashed_messages() %}41     {% if messages %}42       <ul class=flashes>43       {% for message in messages %}44         <li>{{ message }}</li>45       {% endfor %}46       </ul>47     {% endif %}48   {% endwith %}49   {% block body %}{% endblock %}5051And here the index.html template:5253.. sourcecode:: html+jinja5455   {% extends "layout.html" %}56   {% block body %}57     <h1>Overview</h1>58     <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>59   {% endblock %}6061And of course the login template:6263.. sourcecode:: html+jinja6465   {% extends "layout.html" %}66   {% block body %}67     <h1>Login</h1>68     {% if error %}69       <p class=error><strong>Error:</strong> {{ error }}70     {% endif %}71     <form action="" method=post>72       <dl>73         <dt>Username:74         <dd><input type=text name=username value="{{75             request.form.username }}">76         <dt>Password:77         <dd><input type=password name=password>78       </dl>79       <p><input type=submit value=Login>80     </form>81   {% endblock %}