messages.txt 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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 in
  42. :mod:`django.contrib.messages`:
  43. .. class:: storage.session.SessionStorage
  44. This class stores all messages inside of the request's session. Therefore
  45. it requires Django's ``contrib.sessions`` application.
  46. .. class:: storage.cookie.CookieStorage
  47. This class stores the message data in a cookie (signed with a secret hash
  48. to prevent manipulation) to persist notifications across requests. Old
  49. messages are dropped if the cookie data size would exceed 2048 bytes.
  50. .. class:: storage.fallback.FallbackStorage
  51. This class first uses ``CookieStorage``, and falls back to using
  52. ``SessionStorage`` for the messages that could not fit in a single cookie.
  53. It also requires Django's ``contrib.sessions`` application.
  54. This behavior avoids writing to the session whenever possible. It should
  55. provide the best performance in the general case.
  56. :class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the
  57. default storage class. If it isn't suitable to your needs, you can select
  58. another storage class by setting :setting:`MESSAGE_STORAGE` to its full import
  59. path, for example::
  60. MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
  61. .. class:: storage.base.BaseStorage
  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-level:
  66. Message levels
  67. --------------
  68. The messages framework is based on a configurable level architecture similar
  69. to that of the Python logging module. Message levels allow you to group
  70. messages by type so they can be filtered or displayed differently in views and
  71. templates.
  72. The built-in levels, which can be imported from ``django.contrib.messages``
  73. directly, are:
  74. =========== ========
  75. Constant Purpose
  76. =========== ========
  77. ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
  78. ``INFO`` Informational messages for the user
  79. ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
  80. ``WARNING`` A failure did not occur but may be imminent
  81. ``ERROR`` An action was **not** successful or some other failure occurred
  82. =========== ========
  83. The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
  84. (or it can be `changed per request`_). Attempts to add messages of a level less
  85. than this will be ignored.
  86. .. _`changed per request`: `Changing the minimum recorded level per-request`_
  87. Message tags
  88. ------------
  89. Message tags are a string representation of the message level plus any
  90. extra tags that were added directly in the view (see
  91. `Adding extra message tags`_ below for more details). Tags are stored in a
  92. string and are separated by spaces. Typically, message tags
  93. are used as CSS classes to customize message style based on message type. By
  94. default, each level has a single tag that's a lowercase version of its own
  95. constant:
  96. ============== ===========
  97. Level Constant Tag
  98. ============== ===========
  99. ``DEBUG`` ``debug``
  100. ``INFO`` ``info``
  101. ``SUCCESS`` ``success``
  102. ``WARNING`` ``warning``
  103. ``ERROR`` ``error``
  104. ============== ===========
  105. To change the default tags for a message level (either built-in or custom),
  106. set the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels
  107. you wish to change. As this extends the default tags, you only need to provide
  108. tags for the levels you wish to override::
  109. from django.contrib.messages import constants as messages
  110. MESSAGE_TAGS = {
  111. messages.INFO: '',
  112. 50: 'critical',
  113. }
  114. Using messages in views and templates
  115. =====================================
  116. .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
  117. Adding a message
  118. ----------------
  119. To add a message, call::
  120. from django.contrib import messages
  121. messages.add_message(request, messages.INFO, 'Hello world.')
  122. Some shortcut methods provide a standard way to add messages with commonly
  123. used tags (which are usually represented as HTML classes for the message)::
  124. messages.debug(request, '%s SQL statements were executed.' % count)
  125. messages.info(request, 'Three credits remain in your account.')
  126. messages.success(request, 'Profile details updated.')
  127. messages.warning(request, 'Your account expires in three days.')
  128. messages.error(request, 'Document deleted.')
  129. .. _message-displaying:
  130. Displaying messages
  131. -------------------
  132. In your template, use something like::
  133. {% if messages %}
  134. <ul class="messages">
  135. {% for message in messages %}
  136. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  137. {% endfor %}
  138. </ul>
  139. {% endif %}
  140. If you're using the context processor, your template should be rendered with a
  141. ``RequestContext``. Otherwise, ensure ``messages`` is available to
  142. the template context.
  143. Even if you know there is only just one message, you should still iterate over
  144. the ``messages`` sequence, because otherwise the message storage will not be cleared
  145. for the next request.
  146. .. versionadded:: 1.7
  147. The context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which
  148. is a mapping of the message level names to their numeric value::
  149. {% if messages %}
  150. <ul class="messages">
  151. {% for message in messages %}
  152. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
  153. {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
  154. {{ message }}
  155. </li>
  156. {% endfor %}
  157. </ul>
  158. {% endif %}
  159. The ``Message`` class
  160. ---------------------
  161. .. class:: storage.base.Message
  162. When you loop over the list of messages in a template, what you get are
  163. instances of the ``Message`` class. It's quite a simple object, with only a
  164. few attributes:
  165. * ``message``: The actual text of the message.
  166. * ``level``: An integer describing the type of the message (see the
  167. `message levels`_ section above).
  168. * ``tags``: A string combining all the message's tags (``extra_tags`` and
  169. ``level_tag``) separated by spaces.
  170. * ``extra_tags``: A string containing custom tags for this message,
  171. separated by spaces. It's empty by default.
  172. .. versionadded:: 1.7
  173. * ``level_tag``: The string representation of the level. By default, it's
  174. the lowercase version of the name of the associated constant, but this
  175. can be changed if you need by using the :setting:`MESSAGE_TAGS` setting.
  176. Creating custom message levels
  177. ------------------------------
  178. Messages levels are nothing more than integers, so you can define your own
  179. level constants and use them to create more customized user feedback, e.g.::
  180. CRITICAL = 50
  181. def my_view(request):
  182. messages.add_message(request, CRITICAL, 'A serious error occurred.')
  183. When creating custom message levels you should be careful to avoid overloading
  184. existing levels. The values for the built-in levels are:
  185. .. _message-level-constants:
  186. ============== =====
  187. Level Constant Value
  188. ============== =====
  189. ``DEBUG`` 10
  190. ``INFO`` 20
  191. ``SUCCESS`` 25
  192. ``WARNING`` 30
  193. ``ERROR`` 40
  194. ============== =====
  195. If you need to identify the custom levels in your HTML or CSS, you need to
  196. provide a mapping via the :setting:`MESSAGE_TAGS` setting.
  197. .. note::
  198. If you are creating a reusable application, it is recommended to use
  199. only the built-in `message levels`_ and not rely on any custom levels.
  200. Changing the minimum recorded level per-request
  201. -----------------------------------------------
  202. The minimum recorded level can be set per request via the ``set_level``
  203. method::
  204. from django.contrib import messages
  205. # Change the messages level to ensure the debug message is added.
  206. messages.set_level(request, messages.DEBUG)
  207. messages.debug(request, 'Test message...')
  208. # In another request, record only messages with a level of WARNING and higher
  209. messages.set_level(request, messages.WARNING)
  210. messages.success(request, 'Your profile was updated.') # ignored
  211. messages.warning(request, 'Your account is about to expire.') # recorded
  212. # Set the messages level back to default.
  213. messages.set_level(request, None)
  214. Similarly, the current effective level can be retrieved with ``get_level``::
  215. from django.contrib import messages
  216. current_level = messages.get_level(request)
  217. For more information on how the minimum recorded level functions, see
  218. `Message levels`_ above.
  219. Adding extra message tags
  220. -------------------------
  221. For more direct control over message tags, you can optionally provide a string
  222. containing extra tags to any of the add methods::
  223. messages.add_message(request, messages.INFO, 'Over 9000!',
  224. extra_tags='dragonball')
  225. messages.error(request, 'Email box full', extra_tags='email')
  226. Extra tags are added before the default tag for that level and are space
  227. separated.
  228. Failing silently when the message framework is disabled
  229. -------------------------------------------------------
  230. If you're writing a reusable app (or other piece of code) and want to include
  231. messaging functionality, but don't want to require your users to enable it
  232. if they don't want to, you may pass an additional keyword argument
  233. ``fail_silently=True`` to any of the ``add_message`` family of methods. For
  234. example::
  235. messages.add_message(request, messages.SUCCESS, 'Profile details updated.',
  236. fail_silently=True)
  237. messages.info(request, 'Hello world.', fail_silently=True)
  238. .. note::
  239. Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
  240. otherwise occur when the messages framework disabled and one attempts to
  241. use one of the ``add_message`` family of methods. It does not hide failures
  242. that may occur for other reasons.
  243. Adding messages in Class Based Views
  244. ------------------------------------
  245. .. versionadded:: 1.6
  246. .. class:: views.SuccessMessageMixin
  247. Adds a success message attribute to
  248. :class:`~django.views.generic.edit.FormView` based classes
  249. .. method:: get_success_message(cleaned_data)
  250. ``cleaned_data`` is the cleaned data from the form which is used for
  251. string formatting
  252. **Example views.py**::
  253. from django.contrib.messages.views import SuccessMessageMixin
  254. from django.views.generic.edit import CreateView
  255. from myapp.models import Author
  256. class AuthorCreate(SuccessMessageMixin, CreateView):
  257. model = Author
  258. success_url = '/success/'
  259. success_message = "%(name)s was created successfully"
  260. The cleaned data from the ``form`` is available for string interpolation using
  261. the ``%(field_name)s`` syntax. For ModelForms, if you need access to fields
  262. from the saved ``object`` override the
  263. :meth:`~django.contrib.messages.views.SuccessMessageMixin.get_success_message`
  264. method.
  265. **Example views.py for ModelForms**::
  266. from django.contrib.messages.views import SuccessMessageMixin
  267. from django.views.generic.edit import CreateView
  268. from myapp.models import ComplicatedModel
  269. class ComplicatedCreate(SuccessMessageMixin, CreateView):
  270. model = ComplicatedModel
  271. success_url = '/success/'
  272. success_message = "%(calculated_field)s was created successfully"
  273. def get_success_message(self, cleaned_data):
  274. return self.success_message % dict(cleaned_data,
  275. calculated_field=self.object.calculated_field)
  276. Expiration of messages
  277. ======================
  278. The messages are marked to be cleared when the storage instance is iterated
  279. (and cleared when the response is processed).
  280. To avoid the messages being cleared, you can set the messages storage to
  281. ``False`` after iterating::
  282. storage = messages.get_messages(request)
  283. for message in storage:
  284. do_something_with(message)
  285. storage.used = False
  286. Behavior of parallel requests
  287. =============================
  288. Due to the way cookies (and hence sessions) work, **the behavior of any
  289. backends that make use of cookies or sessions is undefined when the same
  290. client makes multiple requests that set or get messages in parallel**. For
  291. example, if a client initiates a request that creates a message in one window
  292. (or tab) and then another that fetches any uniterated messages in another
  293. window, before the first window redirects, the message may appear in the
  294. second window instead of the first window where it may be expected.
  295. In short, when multiple simultaneous requests from the same client are
  296. involved, messages are not guaranteed to be delivered to the same window that
  297. created them nor, in some cases, at all. Note that this is typically not a
  298. problem in most applications and will become a non-issue in HTML5, where each
  299. window/tab will have its own browsing context.
  300. Settings
  301. ========
  302. A few :ref:`settings<settings-messages>` give you control over message
  303. behavior:
  304. * :setting:`MESSAGE_LEVEL`
  305. * :setting:`MESSAGE_STORAGE`
  306. * :setting:`MESSAGE_TAGS`
  307. .. versionadded:: 1.7
  308. For backends that use cookies, the settings for the cookie are taken from
  309. the session cookie settings:
  310. * :setting:`SESSION_COOKIE_DOMAIN`
  311. * :setting:`SESSION_COOKIE_SECURE`
  312. * :setting:`SESSION_COOKIE_HTTPONLY`