The messages framework

Quite commonly in web applications, you need to display a one-timenotification message (also known as "flash message") to the user afterprocessing a form or some other types of user input.

For this, Django provides full support for cookie- and session-basedmessaging, for both anonymous and authenticated users. The messages frameworkallows you to temporarily store messages in one request and retrieve them fordisplay in a subsequent request (usually the next one). Every message istagged with a specific level that determines its priority (e.g., info,warning, or error).

Enabling messages

Messages are implemented through a middlewareclass and corresponding context processor.

The default settings.py created by django-admin startprojectalready contains all the settings required to enable message functionality:

  • 'django.contrib.messages' is in INSTALLED_APPS.

  • MIDDLEWARE contains'django.contrib.sessions.middleware.SessionMiddleware' and'django.contrib.messages.middleware.MessageMiddleware'.

The default storage backend relies onsessions. That's why SessionMiddlewaremust be enabled and appear before MessageMiddleware inMIDDLEWARE.

  • The 'context_processors' option of the DjangoTemplates backenddefined in your TEMPLATES setting contains'django.contrib.messages.context_processors.messages'.

If you don't want to use messages, you can remove'django.contrib.messages' from your INSTALLED_APPS, theMessageMiddleware line from MIDDLEWARE, and the messagescontext processor from TEMPLATES.

Configuring the message engine

Storage backends

The messages framework can use different backends to store temporary messages.

Django provides three built-in storage classes indjango.contrib.messages:

  • class storage.session.SessionStorage
  • This class stores all messages inside of the request's session. Thereforeit requires Django's contrib.sessions application.

  • class storage.cookie.CookieStorage

  • This class stores the message data in a cookie (signed with a secret hashto prevent manipulation) to persist notifications across requests. Oldmessages are dropped if the cookie data size would exceed 2048 bytes.

  • class storage.fallback.FallbackStorage

  • This class first uses CookieStorage, and falls back to usingSessionStorage for the messages that could not fit in a single cookie.It also requires Django's contrib.sessions application.

This behavior avoids writing to the session whenever possible. It shouldprovide the best performance in the general case.

FallbackStorage is thedefault storage class. If it isn't suitable to your needs, you can selectanother storage class by setting MESSAGE_STORAGE to its full importpath, for example:

  1. MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
  • class storage.base.BaseStorage
  • To write your own storage class, subclass the BaseStorage class indjango.contrib.messages.storage.base and implement the _get and_store methods.

Message levels

The messages framework is based on a configurable level architecture similarto that of the Python logging module. Message levels allow you to groupmessages by type so they can be filtered or displayed differently in views andtemplates.

The built-in levels, which can be imported from django.contrib.messagesdirectly, are:

ConstantPurpose
DEBUGDevelopment-related messages that will be ignored (or removed) in a production deployment
INFOInformational messages for the user
SUCCESSAn action was successful, e.g. "Your profile was updated successfully"
WARNINGA failure did not occur but may be imminent
ERRORAn action was not successful or some other failure occurred

The MESSAGE_LEVEL setting can be used to change the minimum recorded level(or it can be changed per request). Attempts to add messages of a level lessthan this will be ignored.

Message tags

Message tags are a string representation of the message level plus anyextra tags that were added directly in the view (seeAdding extra message tags below for more details). Tags are stored in astring and are separated by spaces. Typically, message tagsare used as CSS classes to customize message style based on message type. Bydefault, each level has a single tag that's a lowercase version of its ownconstant:

Level ConstantTag
DEBUGdebug
INFOinfo
SUCCESSsuccess
WARNINGwarning
ERRORerror

To change the default tags for a message level (either built-in or custom),set the MESSAGE_TAGS setting to a dictionary containing the levelsyou wish to change. As this extends the default tags, you only need to providetags for the levels you wish to override:

  1. from django.contrib.messages import constants as messages
  2. MESSAGE_TAGS = {
  3. messages.INFO: '',
  4. 50: 'critical',
  5. }

Using messages in views and templates

  • addmessage(_request, level, message, extra_tags='', fail_silently=False)[源代码]

Adding a message

To add a message, call:

  1. from django.contrib import messages
  2. messages.add_message(request, messages.INFO, 'Hello world.')

Some shortcut methods provide a standard way to add messages with commonlyused tags (which are usually represented as HTML classes for the message):

  1. messages.debug(request, '%s SQL statements were executed.' % count)
  2. messages.info(request, 'Three credits remain in your account.')
  3. messages.success(request, 'Profile details updated.')
  4. messages.warning(request, 'Your account expires in three days.')
  5. messages.error(request, 'Document deleted.')

Displaying messages

  • getmessages(_request)[源代码]
  • In your template, use something like:
  1. {% if messages %}
  2. <ul class="messages">
  3. {% for message in messages %}
  4. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  5. {% endfor %}
  6. </ul>
  7. {% endif %}

If you're using the context processor, your template should be rendered with aRequestContext. Otherwise, ensure messages is available tothe template context.

Even if you know there is only just one message, you should still iterate overthe messages sequence, because otherwise the message storage will not be clearedfor the next request.

The context processor also provides a DEFAULT_MESSAGE_LEVELS variable whichis a mapping of the message level names to their numeric value:

  1. {% if messages %}
  2. <ul class="messages">
  3. {% for message in messages %}
  4. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
  5. {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
  6. {{ message }}
  7. </li>
  8. {% endfor %}
  9. </ul>
  10. {% endif %}

Outside of templates, you can useget_messages():

  1. from django.contrib.messages import get_messages
  2.  
  3. storage = get_messages(request)
  4. for message in storage:
  5. do_something_with_the_message(message)

For instance, you can fetch all the messages to return them in aJSONResponseMixin instead of aTemplateResponseMixin.

get_messages() will return aninstance of the configured storage backend.

The Message class

  • class storage.base.Message
  • When you loop over the list of messages in a template, what you get areinstances of the Message class. It's quite a simple object, with only afew attributes:

    • message: The actual text of the message.
    • level: An integer describing the type of the message (see themessage levels section above).
    • tags: A string combining all the message's tags (extra_tags andlevel_tag) separated by spaces.
    • extra_tags: A string containing custom tags for this message,separated by spaces. It's empty by default.
    • level_tag: The string representation of the level. By default, it'sthe lowercase version of the name of the associated constant, but thiscan be changed if you need by using the MESSAGE_TAGS setting.

Creating custom message levels

Messages levels are nothing more than integers, so you can define your ownlevel constants and use them to create more customized user feedback, e.g.:

  1. CRITICAL = 50
  2.  
  3. def my_view(request):
  4. messages.add_message(request, CRITICAL, 'A serious error occurred.')

When creating custom message levels you should be careful to avoid overloadingexisting levels. The values for the built-in levels are:

Level ConstantValue
DEBUG10
INFO20
SUCCESS25
WARNING30
ERROR40

If you need to identify the custom levels in your HTML or CSS, you need toprovide a mapping via the MESSAGE_TAGS setting.

注解

If you are creating a reusable application, it is recommended to useonly the built-in message levels and not rely on any custom levels.

Changing the minimum recorded level per-request

The minimum recorded level can be set per request via the set_levelmethod:

  1. from django.contrib import messages
  2.  
  3. # Change the messages level to ensure the debug message is added.
  4. messages.set_level(request, messages.DEBUG)
  5. messages.debug(request, 'Test message...')
  6.  
  7. # In another request, record only messages with a level of WARNING and higher
  8. messages.set_level(request, messages.WARNING)
  9. messages.success(request, 'Your profile was updated.') # ignored
  10. messages.warning(request, 'Your account is about to expire.') # recorded
  11.  
  12. # Set the messages level back to default.
  13. messages.set_level(request, None)

Similarly, the current effective level can be retrieved with get_level:

  1. from django.contrib import messages
  2. current_level = messages.get_level(request)

For more information on how the minimum recorded level functions, seeMessage levels above.

Adding extra message tags

For more direct control over message tags, you can optionally provide a stringcontaining extra tags to any of the add methods:

  1. messages.add_message(request, messages.INFO, 'Over 9000!', extra_tags='dragonball')
  2. messages.error(request, 'Email box full', extra_tags='email')

Extra tags are added before the default tag for that level and are spaceseparated.

Failing silently when the message framework is disabled

If you're writing a reusable app (or other piece of code) and want to includemessaging functionality, but don't want to require your users to enable itif they don't want to, you may pass an additional keyword argumentfail_silently=True to any of the add_message family of methods. Forexample:

  1. messages.add_message(
  2. request, messages.SUCCESS, 'Profile details updated.',
  3. fail_silently=True,
  4. )
  5. messages.info(request, 'Hello world.', fail_silently=True)

注解

Setting fail_silently=True only hides the MessageFailure that wouldotherwise occur when the messages framework disabled and one attempts touse one of the add_message family of methods. It does not hide failuresthat may occur for other reasons.

Adding messages in class-based views

  • class views.SuccessMessageMixin
  • Adds a success message attribute toFormView based classes

    • getsuccess_message(_cleaned_data)
    • cleaned_data is the cleaned data from the form which is used forstring formatting

Example views.py:

  1. from django.contrib.messages.views import SuccessMessageMixin
  2. from django.views.generic.edit import CreateView
  3. from myapp.models import Author
  4.  
  5. class AuthorCreate(SuccessMessageMixin, CreateView):
  6. model = Author
  7. success_url = '/success/'
  8. success_message = "%(name)s was created successfully"

The cleaned data from the form is available for string interpolation usingthe %(field_name)s syntax. For ModelForms, if you need access to fieldsfrom the saved object override theget_success_message()method.

Example views.py for ModelForms:

  1. from django.contrib.messages.views import SuccessMessageMixin
  2. from django.views.generic.edit import CreateView
  3. from myapp.models import ComplicatedModel
  4.  
  5. class ComplicatedCreate(SuccessMessageMixin, CreateView):
  6. model = ComplicatedModel
  7. success_url = '/success/'
  8. success_message = "%(calculated_field)s was created successfully"
  9.  
  10. def get_success_message(self, cleaned_data):
  11. return self.success_message % dict(
  12. cleaned_data,
  13. calculated_field=self.object.calculated_field,
  14. )

Expiration of messages

The messages are marked to be cleared when the storage instance is iterated(and cleared when the response is processed).

To avoid the messages being cleared, you can set the messages storage toFalse after iterating:

  1. storage = messages.get_messages(request)
  2. for message in storage:
  3. do_something_with(message)
  4. storage.used = False

Behavior of parallel requests

Due to the way cookies (and hence sessions) work, the behavior of anybackends that make use of cookies or sessions is undefined when the sameclient makes multiple requests that set or get messages in parallel. Forexample, if a client initiates a request that creates a message in one window(or tab) and then another that fetches any uniterated messages in anotherwindow, before the first window redirects, the message may appear in thesecond window instead of the first window where it may be expected.

In short, when multiple simultaneous requests from the same client areinvolved, messages are not guaranteed to be delivered to the same window thatcreated them nor, in some cases, at all. Note that this is typically not aproblem in most applications and will become a non-issue in HTML5, where eachwindow/tab will have its own browsing context.

Settings

A few settings give you control over messagebehavior: