messages.txt 14 KB

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