messages.txt 15 KB

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