Skip to content
Myr

flashing.rst

This file

Path

docs/patterns/flashing.rst

151 lines · 4.2 KiB

Last changed by

Fix Message Flashing doc, from SwashBuckla #pocoo.Ron DuPlainbefore adoption5cb50a4

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 they 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.1314Simple Flashing15---------------1617So here is a full example::1819    from flask import Flask, flash, redirect, render_template, \20         request, url_for2122    app = Flask(__name__)23    app.secret_key = 'some_secret'2425    @app.route('/')26    def index():27        return render_template('index.html')2829    @app.route('/login', methods=['GET', 'POST'])30    def login():31        error = None32        if request.method == 'POST':33            if request.form['username'] != 'admin' or \34                    request.form['password'] != 'secret':35                error = 'Invalid credentials'36            else:37                flash('You were successfully logged in')38                return redirect(url_for('index'))39        return render_template('login.html', error=error)4041    if __name__ == "__main__":42        app.run()434445And here the ``layout.html`` template which does the magic:4647.. sourcecode:: html+jinja4849   <!doctype html>50   <title>My Application</title>51   {% with messages = get_flashed_messages() %}52     {% if messages %}53       <ul class=flashes>54       {% for message in messages %}55         <li>{{ message }}</li>56       {% endfor %}57       </ul>58     {% endif %}59   {% endwith %}60   {% block body %}{% endblock %}6162And here the index.html template:6364.. sourcecode:: html+jinja6566   {% extends "layout.html" %}67   {% block body %}68     <h1>Overview</h1>69     <p>Do you want to <a href="{{ url_for('login') }}">log in?</a>70   {% endblock %}7172And of course the login template:7374.. sourcecode:: html+jinja7576   {% extends "layout.html" %}77   {% block body %}78     <h1>Login</h1>79     {% if error %}80       <p class=error><strong>Error:</strong> {{ error }}81     {% endif %}82     <form action="" method=post>83       <dl>84         <dt>Username:85         <dd><input type=text name=username value="{{86             request.form.username }}">87         <dt>Password:88         <dd><input type=password name=password>89       </dl>90       <p><input type=submit value=Login>91     </form>92   {% endblock %}9394Flashing With Categories95------------------------9697.. versionadded:: 0.39899It is also possible to provide categories when flashing a message.  The100default category if nothing is provided is ``'message'``.  Alternative101categories can be used to give the user better feedback.  For example102error messages could be displayed with a red background.103104To flash a message with a different category, just use the second argument105to the :func:`~flask.flash` function::106107    flash(u'Invalid password provided', 'error')108109Inside the template you then have to tell the110:func:`~flask.get_flashed_messages` function to also return the111categories.  The loop looks slightly different in that situation then:112113.. sourcecode:: html+jinja114115   {% with messages = get_flashed_messages(with_categories=true) %}116     {% if messages %}117       <ul class=flashes>118       {% for category, message in messages %}119         <li class="{{ category }}">{{ message }}</li>120       {% endfor %}121       </ul>122     {% endif %}123   {% endwith %}124125This is just one example of how to render these flashed messages.  One126might also use the category to add a prefix such as127``<strong>Error:</strong>`` to the message.128129Filtering Flash Messages130------------------------131132.. versionadded:: 0.9133134Optionally you can pass a list of categories which filters the results of135:func:`~flask.get_flashed_messages`.  This is useful if you wish to136render each category in a separate block.137138.. sourcecode:: html+jinja139140    {% with errors = get_flashed_messages(category_filter=["error"]) %}141    {% if errors %}142    <div class="alert-message block-message error">143      <a class="close" href="#">×</a>144      <ul>145        {%- for msg in errors %}146        <li>{{ msg }}</li>147        {% endfor -%}148      </ul>149    </div>150    {% endif %}151    {% endwith %}