messages.txt 16 KB

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