1. ======================
    
  2. The messages framework
    
  3. ======================
    
  4. 
    
  5. .. module:: django.contrib.messages
    
  6.    :synopsis: Provides cookie- and session-based temporary message storage.
    
  7. 
    
  8. Quite commonly in web applications, you need to display a one-time
    
  9. notification message (also known as "flash message") to the user after
    
  10. processing a form or some other types of user input.
    
  11. 
    
  12. For this, Django provides full support for cookie- and session-based
    
  13. messaging, for both anonymous and authenticated users. The messages framework
    
  14. allows you to temporarily store messages in one request and retrieve them for
    
  15. display in a subsequent request (usually the next one). Every message is
    
  16. tagged with a specific ``level`` that determines its priority (e.g., ``info``,
    
  17. ``warning``, or ``error``).
    
  18. 
    
  19. Enabling messages
    
  20. =================
    
  21. 
    
  22. Messages are implemented through a :doc:`middleware </ref/middleware>`
    
  23. class and corresponding :doc:`context processor </ref/templates/api>`.
    
  24. 
    
  25. The default ``settings.py`` created by ``django-admin startproject``
    
  26. already contains all the settings required to enable message functionality:
    
  27. 
    
  28. * ``'django.contrib.messages'`` is in :setting:`INSTALLED_APPS`.
    
  29. 
    
  30. * :setting:`MIDDLEWARE` contains
    
  31.   ``'django.contrib.sessions.middleware.SessionMiddleware'`` and
    
  32.   ``'django.contrib.messages.middleware.MessageMiddleware'``.
    
  33. 
    
  34.   The default :ref:`storage backend <message-storage-backends>` relies on
    
  35.   :doc:`sessions </topics/http/sessions>`. That's why ``SessionMiddleware``
    
  36.   must be enabled and appear before ``MessageMiddleware`` in
    
  37.   :setting:`MIDDLEWARE`.
    
  38. 
    
  39. * The ``'context_processors'`` option of the ``DjangoTemplates`` backend
    
  40.   defined in your :setting:`TEMPLATES` setting contains
    
  41.   ``'django.contrib.messages.context_processors.messages'``.
    
  42. 
    
  43. If you don't want to use messages, you can remove
    
  44. ``'django.contrib.messages'`` from your :setting:`INSTALLED_APPS`, the
    
  45. ``MessageMiddleware`` line from :setting:`MIDDLEWARE`, and the ``messages``
    
  46. context processor from :setting:`TEMPLATES`.
    
  47. 
    
  48. Configuring the message engine
    
  49. ==============================
    
  50. 
    
  51. .. _message-storage-backends:
    
  52. 
    
  53. Storage backends
    
  54. ----------------
    
  55. 
    
  56. The messages framework can use different backends to store temporary messages.
    
  57. 
    
  58. Django provides three built-in storage classes in
    
  59. :mod:`django.contrib.messages`:
    
  60. 
    
  61. .. class:: storage.session.SessionStorage
    
  62. 
    
  63.     This class stores all messages inside of the request's session. Therefore
    
  64.     it requires Django's ``contrib.sessions`` application.
    
  65. 
    
  66. .. class:: storage.cookie.CookieStorage
    
  67. 
    
  68.     This class stores the message data in a cookie (signed with a secret hash
    
  69.     to prevent manipulation) to persist notifications across requests. Old
    
  70.     messages are dropped if the cookie data size would exceed 2048 bytes.
    
  71. 
    
  72. .. class:: storage.fallback.FallbackStorage
    
  73. 
    
  74.     This class first uses ``CookieStorage``, and falls back to using
    
  75.     ``SessionStorage`` for the messages that could not fit in a single cookie.
    
  76.     It also requires Django's ``contrib.sessions`` application.
    
  77. 
    
  78.     This behavior avoids writing to the session whenever possible. It should
    
  79.     provide the best performance in the general case.
    
  80. 
    
  81. :class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the
    
  82. default storage class. If it isn't suitable to your needs, you can select
    
  83. another storage class by setting :setting:`MESSAGE_STORAGE` to its full import
    
  84. path, for example::
    
  85. 
    
  86.     MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
    
  87. 
    
  88. .. class:: storage.base.BaseStorage
    
  89. 
    
  90. To write your own storage class, subclass the ``BaseStorage`` class in
    
  91. ``django.contrib.messages.storage.base`` and implement the ``_get`` and
    
  92. ``_store`` methods.
    
  93. 
    
  94. .. _message-level:
    
  95. 
    
  96. Message levels
    
  97. --------------
    
  98. 
    
  99. The messages framework is based on a configurable level architecture similar
    
  100. to that of the Python logging module. Message levels allow you to group
    
  101. messages by type so they can be filtered or displayed differently in views and
    
  102. templates.
    
  103. 
    
  104. The built-in levels, which can be imported from ``django.contrib.messages``
    
  105. directly, are:
    
  106. 
    
  107. =========== ========
    
  108. Constant    Purpose
    
  109. =========== ========
    
  110. ``DEBUG``   Development-related messages that will be ignored (or removed) in a production deployment
    
  111. ``INFO``    Informational messages for the user
    
  112. ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
    
  113. ``WARNING`` A failure did not occur but may be imminent
    
  114. ``ERROR``   An action was **not** successful or some other failure occurred
    
  115. =========== ========
    
  116. 
    
  117. The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
    
  118. (or it can be `changed per request`_). Attempts to add messages of a level less
    
  119. than this will be ignored.
    
  120. 
    
  121. .. _`changed per request`: `Changing the minimum recorded level per-request`_
    
  122. 
    
  123. Message tags
    
  124. ------------
    
  125. 
    
  126. Message tags are a string representation of the message level plus any
    
  127. extra tags that were added directly in the view (see
    
  128. `Adding extra message tags`_ below for more details). Tags are stored in a
    
  129. string and are separated by spaces. Typically, message tags
    
  130. are used as CSS classes to customize message style based on message type. By
    
  131. default, each level has a single tag that's a lowercase version of its own
    
  132. constant:
    
  133. 
    
  134. ==============  ===========
    
  135. Level Constant  Tag
    
  136. ==============  ===========
    
  137. ``DEBUG``       ``debug``
    
  138. ``INFO``        ``info``
    
  139. ``SUCCESS``     ``success``
    
  140. ``WARNING``     ``warning``
    
  141. ``ERROR``       ``error``
    
  142. ==============  ===========
    
  143. 
    
  144. To change the default tags for a message level (either built-in or custom),
    
  145. set the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels
    
  146. you wish to change. As this extends the default tags, you only need to provide
    
  147. tags for the levels you wish to override::
    
  148. 
    
  149.     from django.contrib.messages import constants as messages
    
  150.     MESSAGE_TAGS = {
    
  151.         messages.INFO: '',
    
  152.         50: 'critical',
    
  153.     }
    
  154. 
    
  155. Using messages in views and templates
    
  156. =====================================
    
  157. 
    
  158. .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
    
  159. 
    
  160. Adding a message
    
  161. ----------------
    
  162. 
    
  163. To add a message, call::
    
  164. 
    
  165.     from django.contrib import messages
    
  166.     messages.add_message(request, messages.INFO, 'Hello world.')
    
  167. 
    
  168. Some shortcut methods provide a standard way to add messages with commonly
    
  169. used tags (which are usually represented as HTML classes for the message)::
    
  170. 
    
  171.     messages.debug(request, '%s SQL statements were executed.' % count)
    
  172.     messages.info(request, 'Three credits remain in your account.')
    
  173.     messages.success(request, 'Profile details updated.')
    
  174.     messages.warning(request, 'Your account expires in three days.')
    
  175.     messages.error(request, 'Document deleted.')
    
  176. 
    
  177. .. _message-displaying:
    
  178. 
    
  179. Displaying messages
    
  180. -------------------
    
  181. .. function:: get_messages(request)
    
  182. 
    
  183. **In your template**, use something like::
    
  184. 
    
  185.     {% if messages %}
    
  186.     <ul class="messages">
    
  187.         {% for message in messages %}
    
  188.         <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    
  189.         {% endfor %}
    
  190.     </ul>
    
  191.     {% endif %}
    
  192. 
    
  193. If you're using the context processor, your template should be rendered with a
    
  194. ``RequestContext``. Otherwise, ensure ``messages`` is available to
    
  195. the template context.
    
  196. 
    
  197. Even if you know there is only one message, you should still iterate over the
    
  198. ``messages`` sequence, because otherwise the message storage will not be
    
  199. cleared for the next request.
    
  200. 
    
  201. The context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which
    
  202. is a mapping of the message level names to their numeric value::
    
  203. 
    
  204.     {% if messages %}
    
  205.     <ul class="messages">
    
  206.         {% for message in messages %}
    
  207.         <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
    
  208.             {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
    
  209.             {{ message }}
    
  210.         </li>
    
  211.         {% endfor %}
    
  212.     </ul>
    
  213.     {% endif %}
    
  214. 
    
  215. **Outside of templates**, you can use
    
  216. :func:`~django.contrib.messages.get_messages`::
    
  217. 
    
  218.     from django.contrib.messages import get_messages
    
  219. 
    
  220.     storage = get_messages(request)
    
  221.     for message in storage:
    
  222.         do_something_with_the_message(message)
    
  223. 
    
  224. For instance, you can fetch all the messages to return them in a
    
  225. :ref:`JSONResponseMixin <jsonresponsemixin-example>` instead of a
    
  226. :class:`~django.views.generic.base.TemplateResponseMixin`.
    
  227. 
    
  228. :func:`~django.contrib.messages.get_messages` will return an
    
  229. instance of the configured storage backend.
    
  230. 
    
  231. 
    
  232. The ``Message`` class
    
  233. ---------------------
    
  234. 
    
  235. .. class:: storage.base.Message
    
  236. 
    
  237.     When you loop over the list of messages in a template, what you get are
    
  238.     instances of the ``Message`` class. They have only a few attributes:
    
  239. 
    
  240.     * ``message``: The actual text of the message.
    
  241. 
    
  242.     * ``level``: An integer describing the type of the message (see the
    
  243.       `message levels`_ section above).
    
  244. 
    
  245.     * ``tags``: A string combining all the message's tags (``extra_tags`` and
    
  246.       ``level_tag``) separated by spaces.
    
  247. 
    
  248.     * ``extra_tags``: A string containing custom tags for this message,
    
  249.       separated by spaces. It's empty by default.
    
  250. 
    
  251.     * ``level_tag``: The string representation of the level. By default, it's
    
  252.       the lowercase version of the name of the associated constant, but this
    
  253.       can be changed if you need by using the :setting:`MESSAGE_TAGS` setting.
    
  254. 
    
  255. Creating custom message levels
    
  256. ------------------------------
    
  257. 
    
  258. Messages levels are nothing more than integers, so you can define your own
    
  259. level constants and use them to create more customized user feedback, e.g.::
    
  260. 
    
  261.     CRITICAL = 50
    
  262. 
    
  263.     def my_view(request):
    
  264.         messages.add_message(request, CRITICAL, 'A serious error occurred.')
    
  265. 
    
  266. When creating custom message levels you should be careful to avoid overloading
    
  267. existing levels. The values for the built-in levels are:
    
  268. 
    
  269. .. _message-level-constants:
    
  270. 
    
  271. ==============  =====
    
  272. Level Constant  Value
    
  273. ==============  =====
    
  274. ``DEBUG``       10
    
  275. ``INFO``        20
    
  276. ``SUCCESS``     25
    
  277. ``WARNING``     30
    
  278. ``ERROR``       40
    
  279. ==============  =====
    
  280. 
    
  281. If you need to identify the custom levels in your HTML or CSS, you need to
    
  282. provide a mapping via the :setting:`MESSAGE_TAGS` setting.
    
  283. 
    
  284. .. note::
    
  285.    If you are creating a reusable application, it is recommended to use
    
  286.    only the built-in `message levels`_ and not rely on any custom levels.
    
  287. 
    
  288. Changing the minimum recorded level per-request
    
  289. -----------------------------------------------
    
  290. 
    
  291. The minimum recorded level can be set per request via the ``set_level``
    
  292. method::
    
  293. 
    
  294.     from django.contrib import messages
    
  295. 
    
  296.     # Change the messages level to ensure the debug message is added.
    
  297.     messages.set_level(request, messages.DEBUG)
    
  298.     messages.debug(request, 'Test message...')
    
  299. 
    
  300.     # In another request, record only messages with a level of WARNING and higher
    
  301.     messages.set_level(request, messages.WARNING)
    
  302.     messages.success(request, 'Your profile was updated.') # ignored
    
  303.     messages.warning(request, 'Your account is about to expire.') # recorded
    
  304. 
    
  305.     # Set the messages level back to default.
    
  306.     messages.set_level(request, None)
    
  307. 
    
  308. Similarly, the current effective level can be retrieved with ``get_level``::
    
  309. 
    
  310.     from django.contrib import messages
    
  311.     current_level = messages.get_level(request)
    
  312. 
    
  313. For more information on how the minimum recorded level functions, see
    
  314. `Message levels`_ above.
    
  315. 
    
  316. Adding extra message tags
    
  317. -------------------------
    
  318. 
    
  319. For more direct control over message tags, you can optionally provide a string
    
  320. containing extra tags to any of the add methods::
    
  321. 
    
  322.     messages.add_message(request, messages.INFO, 'Over 9000!', extra_tags='dragonball')
    
  323.     messages.error(request, 'Email box full', extra_tags='email')
    
  324. 
    
  325. Extra tags are added before the default tag for that level and are space
    
  326. separated.
    
  327. 
    
  328. Failing silently when the message framework is disabled
    
  329. -------------------------------------------------------
    
  330. 
    
  331. If you're writing a reusable app (or other piece of code) and want to include
    
  332. messaging functionality, but don't want to require your users to enable it
    
  333. if they don't want to, you may pass an additional keyword argument
    
  334. ``fail_silently=True`` to any of the ``add_message`` family of methods. For
    
  335. example::
    
  336. 
    
  337.     messages.add_message(
    
  338.         request, messages.SUCCESS, 'Profile details updated.',
    
  339.         fail_silently=True,
    
  340.     )
    
  341.     messages.info(request, 'Hello world.', fail_silently=True)
    
  342. 
    
  343. .. note::
    
  344.    Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
    
  345.    otherwise occur when the messages framework disabled and one attempts to
    
  346.    use one of the ``add_message`` family of methods. It does not hide failures
    
  347.    that may occur for other reasons.
    
  348. 
    
  349. Adding messages in class-based views
    
  350. ------------------------------------
    
  351. 
    
  352. .. class:: views.SuccessMessageMixin
    
  353. 
    
  354.     Adds a success message attribute to
    
  355.     :class:`~django.views.generic.edit.FormView` based classes
    
  356. 
    
  357.     .. method:: get_success_message(cleaned_data)
    
  358. 
    
  359.         ``cleaned_data`` is the cleaned data from the form which is used for
    
  360.         string formatting
    
  361. 
    
  362. **Example views.py**::
    
  363. 
    
  364.     from django.contrib.messages.views import SuccessMessageMixin
    
  365.     from django.views.generic.edit import CreateView
    
  366.     from myapp.models import Author
    
  367. 
    
  368.     class AuthorCreateView(SuccessMessageMixin, CreateView):
    
  369.         model = Author
    
  370.         success_url = '/success/'
    
  371.         success_message = "%(name)s was created successfully"
    
  372. 
    
  373. The cleaned data from the ``form`` is available for string interpolation using
    
  374. the ``%(field_name)s`` syntax. For ModelForms, if you need access to fields
    
  375. from the saved ``object`` override the
    
  376. :meth:`~django.contrib.messages.views.SuccessMessageMixin.get_success_message`
    
  377. method.
    
  378. 
    
  379. **Example views.py for ModelForms**::
    
  380. 
    
  381.     from django.contrib.messages.views import SuccessMessageMixin
    
  382.     from django.views.generic.edit import CreateView
    
  383.     from myapp.models import ComplicatedModel
    
  384. 
    
  385.     class ComplicatedCreateView(SuccessMessageMixin, CreateView):
    
  386.         model = ComplicatedModel
    
  387.         success_url = '/success/'
    
  388.         success_message = "%(calculated_field)s was created successfully"
    
  389. 
    
  390.         def get_success_message(self, cleaned_data):
    
  391.             return self.success_message % dict(
    
  392.                 cleaned_data,
    
  393.                 calculated_field=self.object.calculated_field,
    
  394.             )
    
  395. 
    
  396. Expiration of messages
    
  397. ======================
    
  398. 
    
  399. The messages are marked to be cleared when the storage instance is iterated
    
  400. (and cleared when the response is processed).
    
  401. 
    
  402. To avoid the messages being cleared, you can set the messages storage to
    
  403. ``False`` after iterating::
    
  404. 
    
  405.     storage = messages.get_messages(request)
    
  406.     for message in storage:
    
  407.         do_something_with(message)
    
  408.     storage.used = False
    
  409. 
    
  410. Behavior of parallel requests
    
  411. =============================
    
  412. 
    
  413. Due to the way cookies (and hence sessions) work, **the behavior of any
    
  414. backends that make use of cookies or sessions is undefined when the same
    
  415. client makes multiple requests that set or get messages in parallel**. For
    
  416. example, if a client initiates a request that creates a message in one window
    
  417. (or tab) and then another that fetches any uniterated messages in another
    
  418. window, before the first window redirects, the message may appear in the
    
  419. second window instead of the first window where it may be expected.
    
  420. 
    
  421. In short, when multiple simultaneous requests from the same client are
    
  422. involved, messages are not guaranteed to be delivered to the same window that
    
  423. created them nor, in some cases, at all. Note that this is typically not a
    
  424. problem in most applications and will become a non-issue in HTML5, where each
    
  425. window/tab will have its own browsing context.
    
  426. 
    
  427. Settings
    
  428. ========
    
  429. 
    
  430. A few :ref:`settings<settings-messages>` give you control over message
    
  431. behavior:
    
  432. 
    
  433. * :setting:`MESSAGE_LEVEL`
    
  434. * :setting:`MESSAGE_STORAGE`
    
  435. * :setting:`MESSAGE_TAGS`
    
  436. 
    
  437. For backends that use cookies, the settings for the cookie are taken from
    
  438. the session cookie settings:
    
  439. 
    
  440. * :setting:`SESSION_COOKIE_DOMAIN`
    
  441. * :setting:`SESSION_COOKIE_SECURE`
    
  442. * :setting:`SESSION_COOKIE_HTTPONLY`