messages.txt 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. ======================
  2. The messages framework
  3. ======================
  4. .. module:: django.contrib.messages
  5. :synopsis: Provides cookie- and session-based temporary message storage.
  6. Quite commonly in web applications, you need to display a one-time
  7. notification message (also known as "flash message") to the user after
  8. processing a form or some other types of user input.
  9. For this, Django provides full support for cookie- and session-based
  10. messaging, for both anonymous and authenticated users. The messages framework
  11. allows you to temporarily store messages in one request and retrieve them for
  12. display in a subsequent request (usually the next one). Every message is
  13. tagged with a specific ``level`` that determines its priority (e.g., ``info``,
  14. ``warning``, or ``error``).
  15. Enabling messages
  16. =================
  17. Messages are implemented through a :doc:`middleware </ref/middleware>`
  18. class and corresponding :doc:`context processor </ref/templates/api>`.
  19. The default ``settings.py`` created by ``django-admin.py startproject``
  20. already contains all the settings required to enable message functionality:
  21. * ``'django.contrib.messages'`` is in :setting:`INSTALLED_APPS`.
  22. * :setting:`MIDDLEWARE_CLASSES` contains
  23. ``'django.contrib.sessions.middleware.SessionMiddleware'`` and
  24. ``'django.contrib.messages.middleware.MessageMiddleware'``.
  25. The default :ref:`storage backend <message-storage-backends>` relies on
  26. :doc:`sessions </topics/http/sessions>`. That's why ``SessionMiddleware``
  27. must be enabled and appear before ``MessageMiddleware`` in
  28. :setting:`MIDDLEWARE_CLASSES`.
  29. * :setting:`TEMPLATE_CONTEXT_PROCESSORS` contains
  30. ``'django.contrib.messages.context_processors.messages'``.
  31. If you don't want to use messages, you can remove
  32. ``'django.contrib.messages'`` from your :setting:`INSTALLED_APPS`, the
  33. ``MessageMiddleware`` line from :setting:`MIDDLEWARE_CLASSES`, and the
  34. ``messages`` context processor from :setting:`TEMPLATE_CONTEXT_PROCESSORS`.
  35. Configuring the message engine
  36. ==============================
  37. .. _message-storage-backends:
  38. Storage backends
  39. ----------------
  40. The messages framework can use different backends to store temporary messages.
  41. Django provides three built-in storage classes:
  42. .. class:: django.contrib.messages.storage.session.SessionStorage
  43. This class stores all messages inside of the request's session. Therefore
  44. it requires Django's ``contrib.sessions`` application.
  45. .. class:: django.contrib.messages.storage.cookie.CookieStorage
  46. This class stores the message data in a cookie (signed with a secret hash
  47. to prevent manipulation) to persist notifications across requests. Old
  48. messages are dropped if the cookie data size would exceed 2048 bytes.
  49. .. class:: django.contrib.messages.storage.fallback.FallbackStorage
  50. This class first uses ``CookieStorage``, and falls back to using
  51. ``SessionStorage`` for the messages that could not fit in a single cookie.
  52. It also requires Django's ``contrib.sessions`` application.
  53. This behavior avoids writing to the session whenever possible. It should
  54. provide the best performance in the general case.
  55. :class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the
  56. default storage class. If it isn't suitable to your needs, you can select
  57. another storage class by setting setting:`MESSAGE_STORAGE` to its full import
  58. path, for example::
  59. MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
  60. To write your own storage class, subclass the ``BaseStorage`` class in
  61. ``django.contrib.messages.storage.base`` and implement the ``_get`` and
  62. ``_store`` methods.
  63. .. _message-level:
  64. Message levels
  65. --------------
  66. The messages framework is based on a configurable level architecture similar
  67. to that of the Python logging module. Message levels allow you to group
  68. messages by type so they can be filtered or displayed differently in views and
  69. templates.
  70. The built-in levels, which can be imported from ``django.contrib.messages``
  71. directly, are:
  72. =========== ========
  73. Constant Purpose
  74. =========== ========
  75. ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
  76. ``INFO`` Informational messages for the user
  77. ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
  78. ``WARNING`` A failure did not occur but may be imminent
  79. ``ERROR`` An action was **not** successful or some other failure occurred
  80. =========== ========
  81. The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
  82. (or it can be `changed per request`_). Attempts to add messages of a level less
  83. than this will be ignored.
  84. .. _`changed per request`: `Changing the minimum recorded level per-request`_
  85. Message tags
  86. ------------
  87. Message tags are a string representation of the message level plus any
  88. extra tags that were added directly in the view (see
  89. `Adding extra message tags`_ below for more details). Tags are stored in a
  90. string and are separated by spaces. Typically, message tags
  91. are used as CSS classes to customize message style based on message type. By
  92. default, each level has a single tag that's a lowercase version of its own
  93. constant:
  94. ============== ===========
  95. Level Constant Tag
  96. ============== ===========
  97. ``DEBUG`` ``debug``
  98. ``INFO`` ``info``
  99. ``SUCCESS`` ``success``
  100. ``WARNING`` ``warning``
  101. ``ERROR`` ``error``
  102. ============== ===========
  103. To change the default tags for a message level (either built-in or custom),
  104. set the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels
  105. you wish to change. As this extends the default tags, you only need to provide
  106. tags for the levels you wish to override::
  107. from django.contrib.messages import constants as messages
  108. MESSAGE_TAGS = {
  109. messages.INFO: '',
  110. 50: 'critical',
  111. }
  112. Using messages in views and templates
  113. =====================================
  114. .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
  115. Adding a message
  116. ----------------
  117. To add a message, call::
  118. from django.contrib import messages
  119. messages.add_message(request, messages.INFO, 'Hello world.')
  120. Some shortcut methods provide a standard way to add messages with commonly
  121. used tags (which are usually represented as HTML classes for the message)::
  122. messages.debug(request, '%s SQL statements were executed.' % count)
  123. messages.info(request, 'Three credits remain in your account.')
  124. messages.success(request, 'Profile details updated.')
  125. messages.warning(request, 'Your account expires in three days.')
  126. messages.error(request, 'Document deleted.')
  127. .. _message-displaying:
  128. Displaying messages
  129. -------------------
  130. In your template, use something like::
  131. {% if messages %}
  132. <ul class="messages">
  133. {% for message in messages %}
  134. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  135. {% endfor %}
  136. </ul>
  137. {% endif %}
  138. If you're using the context processor, your template should be rendered with a
  139. ``RequestContext``. Otherwise, ensure ``messages`` is available to
  140. the template context.
  141. Even if you know there is only just one message, you should still iterate over
  142. the ``messages`` sequence, because otherwise the message storage will not be cleared
  143. for the next request.
  144. Creating custom message levels
  145. ------------------------------
  146. Messages levels are nothing more than integers, so you can define your own
  147. level constants and use them to create more customized user feedback, e.g.::
  148. CRITICAL = 50
  149. def my_view(request):
  150. messages.add_message(request, CRITICAL, 'A serious error occurred.')
  151. When creating custom message levels you should be careful to avoid overloading
  152. existing levels. The values for the built-in levels are:
  153. .. _message-level-constants:
  154. ============== =====
  155. Level Constant Value
  156. ============== =====
  157. ``DEBUG`` 10
  158. ``INFO`` 20
  159. ``SUCCESS`` 25
  160. ``WARNING`` 30
  161. ``ERROR`` 40
  162. ============== =====
  163. If you need to identify the custom levels in your HTML or CSS, you need to
  164. provide a mapping via the :setting:`MESSAGE_TAGS` setting.
  165. .. note::
  166. If you are creating a reusable application, it is recommended to use
  167. only the built-in `message levels`_ and not rely on any custom levels.
  168. Changing the minimum recorded level per-request
  169. -----------------------------------------------
  170. The minimum recorded level can be set per request via the ``set_level``
  171. method::
  172. from django.contrib import messages
  173. # Change the messages level to ensure the debug message is added.
  174. messages.set_level(request, messages.DEBUG)
  175. messages.debug(request, 'Test message...')
  176. # In another request, record only messages with a level of WARNING and higher
  177. messages.set_level(request, messages.WARNING)
  178. messages.success(request, 'Your profile was updated.') # ignored
  179. messages.warning(request, 'Your account is about to expire.') # recorded
  180. # Set the messages level back to default.
  181. messages.set_level(request, None)
  182. Similarly, the current effective level can be retrieved with ``get_level``::
  183. from django.contrib import messages
  184. current_level = messages.get_level(request)
  185. For more information on how the minimum recorded level functions, see
  186. `Message levels`_ above.
  187. Adding extra message tags
  188. -------------------------
  189. For more direct control over message tags, you can optionally provide a string
  190. containing extra tags to any of the add methods::
  191. messages.add_message(request, messages.INFO, 'Over 9000!',
  192. extra_tags='dragonball')
  193. messages.error(request, 'Email box full', extra_tags='email')
  194. Extra tags are added before the default tag for that level and are space
  195. separated.
  196. Failing silently when the message framework is disabled
  197. -------------------------------------------------------
  198. If you're writing a reusable app (or other piece of code) and want to include
  199. messaging functionality, but don't want to require your users to enable it
  200. if they don't want to, you may pass an additional keyword argument
  201. ``fail_silently=True`` to any of the ``add_message`` family of methods. For
  202. example::
  203. messages.add_message(request, messages.SUCCESS, 'Profile details updated.',
  204. fail_silently=True)
  205. messages.info(request, 'Hello world.', fail_silently=True)
  206. .. note::
  207. Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
  208. otherwise occur when the messages framework disabled and one attempts to
  209. use one of the ``add_message`` family of methods. It does not hide failures
  210. that may occur for other reasons.
  211. Expiration of messages
  212. ======================
  213. The messages are marked to be cleared when the storage instance is iterated
  214. (and cleared when the response is processed).
  215. To avoid the messages being cleared, you can set the messages storage to
  216. ``False`` after iterating::
  217. storage = messages.get_messages(request)
  218. for message in storage:
  219. do_something_with(message)
  220. storage.used = False
  221. Behavior of parallel requests
  222. =============================
  223. Due to the way cookies (and hence sessions) work, **the behavior of any
  224. backends that make use of cookies or sessions is undefined when the same
  225. client makes multiple requests that set or get messages in parallel**. For
  226. example, if a client initiates a request that creates a message in one window
  227. (or tab) and then another that fetches any uniterated messages in another
  228. window, before the first window redirects, the message may appear in the
  229. second window instead of the first window where it may be expected.
  230. In short, when multiple simultaneous requests from the same client are
  231. involved, messages are not guaranteed to be delivered to the same window that
  232. created them nor, in some cases, at all. Note that this is typically not a
  233. problem in most applications and will become a non-issue in HTML5, where each
  234. window/tab will have its own browsing context.
  235. Settings
  236. ========
  237. A few :ref:`settings<settings-messages>` give you control over message
  238. behavior:
  239. * :setting:`MESSAGE_LEVEL`
  240. * :setting:`MESSAGE_STORAGE`
  241. * :setting:`MESSAGE_TAGS`
  242. * :ref:`SESSION_COOKIE_DOMAIN<messages-session_cookie_domain>`