messages.txt 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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 `MESSAGE_STORAGE`_ to its full import path,
  58. 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 levels
  64. --------------
  65. The messages framework is based on a configurable level architecture similar
  66. to that of the Python logging module. Message levels allow you to group
  67. messages by type so they can be filtered or displayed differently in views and
  68. templates.
  69. The built-in levels, which can be imported from ``django.contrib.messages``
  70. directly, are:
  71. =========== ========
  72. Constant Purpose
  73. =========== ========
  74. ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
  75. ``INFO`` Informational messages for the user
  76. ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
  77. ``WARNING`` A failure did not occur but may be imminent
  78. ``ERROR`` An action was **not** successful or some other failure occurred
  79. =========== ========
  80. The `MESSAGE_LEVEL`_ setting can be used to change the minimum recorded level
  81. (or it can be `changed per request`_). Attempts to add messages of a level less
  82. than this will be ignored.
  83. .. _`changed per request`: `Changing the minimum recorded level per-request`_
  84. Message tags
  85. ------------
  86. Message tags are a string representation of the message level plus any
  87. extra tags that were added directly in the view (see
  88. `Adding extra message tags`_ below for more details). Tags are stored in a
  89. string and are separated by spaces. Typically, message tags
  90. are used as CSS classes to customize message style based on message type. By
  91. default, each level has a single tag that's a lowercase version of its own
  92. constant:
  93. ============== ===========
  94. Level Constant Tag
  95. ============== ===========
  96. ``DEBUG`` ``debug``
  97. ``INFO`` ``info``
  98. ``SUCCESS`` ``success``
  99. ``WARNING`` ``warning``
  100. ``ERROR`` ``error``
  101. ============== ===========
  102. To change the default tags for a message level (either built-in or custom),
  103. set the `MESSAGE_TAGS`_ setting to a dictionary containing the levels
  104. you wish to change. As this extends the default tags, you only need to provide
  105. tags for the levels you wish to override::
  106. from django.contrib.messages import constants as messages
  107. MESSAGE_TAGS = {
  108. messages.INFO: '',
  109. 50: 'critical',
  110. }
  111. Using messages in views and templates
  112. =====================================
  113. .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
  114. Adding a message
  115. ----------------
  116. To add a message, call::
  117. from django.contrib import messages
  118. messages.add_message(request, messages.INFO, 'Hello world.')
  119. Some shortcut methods provide a standard way to add messages with commonly
  120. used tags (which are usually represented as HTML classes for the message)::
  121. messages.debug(request, '%s SQL statements were executed.' % count)
  122. messages.info(request, 'Three credits remain in your account.')
  123. messages.success(request, 'Profile details updated.')
  124. messages.warning(request, 'Your account expires in three days.')
  125. messages.error(request, 'Document deleted.')
  126. Displaying messages
  127. -------------------
  128. In your template, use something like::
  129. {% if messages %}
  130. <ul class="messages">
  131. {% for message in messages %}
  132. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  133. {% endfor %}
  134. </ul>
  135. {% endif %}
  136. If you're using the context processor, your template should be rendered with a
  137. ``RequestContext``. Otherwise, ensure ``messages`` is available to
  138. the template context.
  139. Even if you know there is only just one message, you should still iterate over
  140. the ``messages`` sequence, because otherwise the message storage will not be cleared
  141. for the next request.
  142. Creating custom message levels
  143. ------------------------------
  144. Messages levels are nothing more than integers, so you can define your own
  145. level constants and use them to create more customized user feedback, e.g.::
  146. CRITICAL = 50
  147. def my_view(request):
  148. messages.add_message(request, CRITICAL, 'A serious error occurred.')
  149. When creating custom message levels you should be careful to avoid overloading
  150. existing levels. The values for the built-in levels are:
  151. .. _message-level-constants:
  152. ============== =====
  153. Level Constant Value
  154. ============== =====
  155. ``DEBUG`` 10
  156. ``INFO`` 20
  157. ``SUCCESS`` 25
  158. ``WARNING`` 30
  159. ``ERROR`` 40
  160. ============== =====
  161. If you need to identify the custom levels in your HTML or CSS, you need to
  162. provide a mapping via the `MESSAGE_TAGS`_ setting.
  163. .. note::
  164. If you are creating a reusable application, it is recommended to use
  165. only the built-in `message levels`_ and not rely on any custom levels.
  166. Changing the minimum recorded level per-request
  167. -----------------------------------------------
  168. The minimum recorded level can be set per request via the ``set_level``
  169. method::
  170. from django.contrib import messages
  171. # Change the messages level to ensure the debug message is added.
  172. messages.set_level(request, messages.DEBUG)
  173. messages.debug(request, 'Test message...')
  174. # In another request, record only messages with a level of WARNING and higher
  175. messages.set_level(request, messages.WARNING)
  176. messages.success(request, 'Your profile was updated.') # ignored
  177. messages.warning(request, 'Your account is about to expire.') # recorded
  178. # Set the messages level back to default.
  179. messages.set_level(request, None)
  180. Similarly, the current effective level can be retrieved with ``get_level``::
  181. from django.contrib import messages
  182. current_level = messages.get_level(request)
  183. For more information on how the minimum recorded level functions, see
  184. `Message levels`_ above.
  185. Adding extra message tags
  186. -------------------------
  187. For more direct control over message tags, you can optionally provide a string
  188. containing extra tags to any of the add methods::
  189. messages.add_message(request, messages.INFO, 'Over 9000!',
  190. extra_tags='dragonball')
  191. messages.error(request, 'Email box full', extra_tags='email')
  192. Extra tags are added before the default tag for that level and are space
  193. separated.
  194. Failing silently when the message framework is disabled
  195. -------------------------------------------------------
  196. If you're writing a reusable app (or other piece of code) and want to include
  197. messaging functionality, but don't want to require your users to enable it
  198. if they don't want to, you may pass an additional keyword argument
  199. ``fail_silently=True`` to any of the ``add_message`` family of methods. For
  200. example::
  201. messages.add_message(request, messages.SUCCESS, 'Profile details updated.',
  202. fail_silently=True)
  203. messages.info(request, 'Hello world.', fail_silently=True)
  204. .. note::
  205. Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
  206. otherwise occur when the messages framework disabled and one attempts to
  207. use one of the ``add_message`` family of methods. It does not hide failures
  208. that may occur for other reasons.
  209. Expiration of messages
  210. ======================
  211. The messages are marked to be cleared when the storage instance is iterated
  212. (and cleared when the response is processed).
  213. To avoid the messages being cleared, you can set the messages storage to
  214. ``False`` after iterating::
  215. storage = messages.get_messages(request)
  216. for message in storage:
  217. do_something_with(message)
  218. storage.used = False
  219. Behavior of parallel requests
  220. =============================
  221. Due to the way cookies (and hence sessions) work, **the behavior of any
  222. backends that make use of cookies or sessions is undefined when the same
  223. client makes multiple requests that set or get messages in parallel**. For
  224. example, if a client initiates a request that creates a message in one window
  225. (or tab) and then another that fetches any uniterated messages in another
  226. window, before the first window redirects, the message may appear in the
  227. second window instead of the first window where it may be expected.
  228. In short, when multiple simultaneous requests from the same client are
  229. involved, messages are not guaranteed to be delivered to the same window that
  230. created them nor, in some cases, at all. Note that this is typically not a
  231. problem in most applications and will become a non-issue in HTML5, where each
  232. window/tab will have its own browsing context.
  233. Settings
  234. ========
  235. A few :doc:`Django settings </ref/settings>` give you control over message
  236. behavior:
  237. MESSAGE_LEVEL
  238. -------------
  239. Default: ``messages.INFO``
  240. This sets the minimum message that will be saved in the message storage. See
  241. `Message levels`_ above for more details.
  242. .. admonition:: Important
  243. If you override ``MESSAGE_LEVEL`` in your settings file and rely on any of
  244. the built-in constants, you must import the constants module directly to
  245. avoid the potential for circular imports, e.g.::
  246. from django.contrib.messages import constants as message_constants
  247. MESSAGE_LEVEL = message_constants.DEBUG
  248. If desired, you may specify the numeric values for the constants directly
  249. according to the values in the above :ref:`constants table
  250. <message-level-constants>`.
  251. MESSAGE_STORAGE
  252. ---------------
  253. Default: ``'django.contrib.messages.storage.fallback.FallbackStorage'``
  254. Controls where Django stores message data. Valid values are:
  255. * ``'django.contrib.messages.storage.fallback.FallbackStorage'``
  256. * ``'django.contrib.messages.storage.session.SessionStorage'``
  257. * ``'django.contrib.messages.storage.cookie.CookieStorage'``
  258. See `Storage backends`_ for more details.
  259. MESSAGE_TAGS
  260. ------------
  261. Default::
  262. {messages.DEBUG: 'debug',
  263. messages.INFO: 'info',
  264. messages.SUCCESS: 'success',
  265. messages.WARNING: 'warning',
  266. messages.ERROR: 'error',}
  267. This sets the mapping of message level to message tag, which is typically
  268. rendered as a CSS class in HTML. If you specify a value, it will extend
  269. the default. This means you only have to specify those values which you need
  270. to override. See `Displaying messages`_ above for more details.
  271. .. admonition:: Important
  272. If you override ``MESSAGE_TAGS`` in your settings file and rely on any of
  273. the built-in constants, you must import the ``constants`` module directly to
  274. avoid the potential for circular imports, e.g.::
  275. from django.contrib.messages import constants as message_constants
  276. MESSAGE_TAGS = {message_constants.INFO: ''}
  277. If desired, you may specify the numeric values for the constants directly
  278. according to the values in the above :ref:`constants table
  279. <message-level-constants>`.
  280. SESSION_COOKIE_DOMAIN
  281. ---------------------
  282. Default: ``None``
  283. The storage backends that use cookies -- ``CookieStorage`` and
  284. ``FallbackStorage`` -- use the value of :setting:`SESSION_COOKIE_DOMAIN` in
  285. setting their cookies. See the :doc:`settings documentation </ref/settings>`
  286. for more information on how this works and why you might need to set it.
  287. .. _Django settings: ../settings/