Middleware flash messages in view methods

Flash messages are typically used when users perform an action (e.g. submit a form) and it's necessary to tell them if the action was successful or if there was some kind of error. Other times flash messages are used as one time notifications on web pages to tell users about certain events (e.g. site maintenance or special discounts). Figure 2-5 shows a set of sample flash messages.

Figure 2-5. Web page flash messages

Django flash messages require a Django app, middleware and a template context processor

By default, all Django projects are enabled to support flash messages. However, if you tweaked your project's settings.py file you may have inadvertently disabled flash messages.

In order for Django flash messages to work you must ensure the following values are set in settings.py: The variable INSTALLED_APPS has the django.contrib.messages value, the variable MIDDLEWARE has the django.contrib.messages.middleware.MessageMiddleware value and the context_processors list in OPTIONS of the TEMPLATES variable has the django.contrib.messages.context_processors.messages value.

As you can see in figure 2-5 there can be different types of flash messages, which are technically known as levels. Django follows the standard Syslog standard severity levels and supports five built-in message levels described in table 2-9.

Table 2-9 Django built-in flash messages

Level Constant Tag Value Purpose
DEBUG debug 10 Development-related messages that will be ignored (or removed) in a production deployment
INFO info 20 Informational messages for the user
SUCCESS success 25 An action was successful, e.g. "Contact info was sent successfully"
WARNING warning 30 A failure did not occur but may be imminent
ERROR error 40 An action was not successful or some other failure occurred