2
0

messages.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  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. .. class:: storage.fallback.FallbackStorage
  52. This class first uses ``CookieStorage``, and falls back to using
  53. ``SessionStorage`` for the messages that could not fit in a single cookie.
  54. It also requires Django's ``contrib.sessions`` application.
  55. This behavior avoids writing to the session whenever possible. It should
  56. provide the best performance in the general case.
  57. :class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the
  58. default storage class. If it isn't suitable to your needs, you can select
  59. another storage class by setting :setting:`MESSAGE_STORAGE` to its full import
  60. path, for example::
  61. MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"
  62. .. class:: storage.base.BaseStorage
  63. To write your own storage class, subclass the ``BaseStorage`` class in
  64. ``django.contrib.messages.storage.base`` and implement the ``_get`` and
  65. ``_store`` methods.
  66. .. _message-level:
  67. Message levels
  68. --------------
  69. The messages framework is based on a configurable level architecture similar
  70. to that of the Python logging module. Message levels allow you to group
  71. messages by type so they can be filtered or displayed differently in views and
  72. templates.
  73. The built-in levels, which can be imported from ``django.contrib.messages``
  74. directly, are:
  75. =========== ========
  76. Constant Purpose
  77. =========== ========
  78. ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
  79. ``INFO`` Informational messages for the user
  80. ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
  81. ``WARNING`` A failure did not occur but may be imminent
  82. ``ERROR`` An action was **not** successful or some other failure occurred
  83. =========== ========
  84. The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
  85. (or it can be `changed per request`_). Attempts to add messages of a level less
  86. than this will be ignored.
  87. .. _`changed per request`: `Changing the minimum recorded level per-request`_
  88. Message tags
  89. ------------
  90. Message tags are a string representation of the message level plus any
  91. extra tags that were added directly in the view (see
  92. `Adding extra message tags`_ below for more details). Tags are stored in a
  93. string and are separated by spaces. Typically, message tags
  94. are used as CSS classes to customize message style based on message type. By
  95. default, each level has a single tag that's a lowercase version of its own
  96. constant:
  97. ============== ===========
  98. Level Constant Tag
  99. ============== ===========
  100. ``DEBUG`` ``debug``
  101. ``INFO`` ``info``
  102. ``SUCCESS`` ``success``
  103. ``WARNING`` ``warning``
  104. ``ERROR`` ``error``
  105. ============== ===========
  106. To change the default tags for a message level (either built-in or custom),
  107. set the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels
  108. you wish to change. As this extends the default tags, you only need to provide
  109. tags for the levels you wish to override::
  110. from django.contrib.messages import constants as messages
  111. MESSAGE_TAGS = {
  112. messages.INFO: "",
  113. 50: "critical",
  114. }
  115. Using messages in views and templates
  116. =====================================
  117. .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
  118. Adding a message
  119. ----------------
  120. To add a message, call::
  121. from django.contrib import messages
  122. messages.add_message(request, messages.INFO, "Hello world.")
  123. Some shortcut methods provide a standard way to add messages with commonly
  124. used tags (which are usually represented as HTML classes for the message)::
  125. messages.debug(request, "%s SQL statements were executed." % count)
  126. messages.info(request, "Three credits remain in your account.")
  127. messages.success(request, "Profile details updated.")
  128. messages.warning(request, "Your account expires in three days.")
  129. messages.error(request, "Document deleted.")
  130. .. _message-displaying:
  131. Displaying messages
  132. -------------------
  133. .. function:: get_messages(request)
  134. **In your template**, use something like:
  135. .. code-block:: html+django
  136. {% if messages %}
  137. <ul class="messages">
  138. {% for message in messages %}
  139. <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
  140. {% endfor %}
  141. </ul>
  142. {% endif %}
  143. If you're using the context processor, your template should be rendered with a
  144. ``RequestContext``. Otherwise, ensure ``messages`` is available to
  145. the template context.
  146. Even if you know there is only one message, you should still iterate over the
  147. ``messages`` sequence, because otherwise the message storage will not be
  148. cleared for the next request.
  149. The context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which
  150. is a mapping of the message level names to their numeric value:
  151. .. code-block:: html+django
  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:: 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,
  248. messages.SUCCESS,
  249. "Profile details updated.",
  250. fail_silently=True,
  251. )
  252. messages.info(request, "Hello world.", fail_silently=True)
  253. .. note::
  254. Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
  255. otherwise occur when the messages framework disabled and one attempts to
  256. use one of the ``add_message`` family of methods. It does not hide failures
  257. that may occur for other reasons.
  258. Adding messages in class-based views
  259. ------------------------------------
  260. .. class:: views.SuccessMessageMixin
  261. Adds a success message attribute to
  262. :class:`~django.views.generic.edit.FormView` based classes
  263. .. method:: get_success_message(cleaned_data)
  264. ``cleaned_data`` is the cleaned data from the form which is used for
  265. string formatting
  266. **Example views.py**::
  267. from django.contrib.messages.views import SuccessMessageMixin
  268. from django.views.generic.edit import CreateView
  269. from myapp.models import Author
  270. class AuthorCreateView(SuccessMessageMixin, CreateView):
  271. model = Author
  272. success_url = "/success/"
  273. success_message = "%(name)s was created successfully"
  274. The cleaned data from the ``form`` is available for string interpolation using
  275. the ``%(field_name)s`` syntax. For ModelForms, if you need access to fields
  276. from the saved ``object`` override the
  277. :meth:`~django.contrib.messages.views.SuccessMessageMixin.get_success_message`
  278. method.
  279. **Example views.py for ModelForms**::
  280. from django.contrib.messages.views import SuccessMessageMixin
  281. from django.views.generic.edit import CreateView
  282. from myapp.models import ComplicatedModel
  283. class ComplicatedCreateView(SuccessMessageMixin, CreateView):
  284. model = ComplicatedModel
  285. success_url = "/success/"
  286. success_message = "%(calculated_field)s was created successfully"
  287. def get_success_message(self, cleaned_data):
  288. return self.success_message % dict(
  289. cleaned_data,
  290. calculated_field=self.object.calculated_field,
  291. )
  292. Expiration of messages
  293. ======================
  294. The messages are marked to be cleared when the storage instance is iterated
  295. (and cleared when the response is processed).
  296. To avoid the messages being cleared, you can set the messages storage to
  297. ``False`` after iterating::
  298. storage = messages.get_messages(request)
  299. for message in storage:
  300. do_something_with(message)
  301. storage.used = False
  302. Behavior of parallel requests
  303. =============================
  304. Due to the way cookies (and hence sessions) work, **the behavior of any
  305. backends that make use of cookies or sessions is undefined when the same
  306. client makes multiple requests that set or get messages in parallel**. For
  307. example, if a client initiates a request that creates a message in one window
  308. (or tab) and then another that fetches any uniterated messages in another
  309. window, before the first window redirects, the message may appear in the
  310. second window instead of the first window where it may be expected.
  311. In short, when multiple simultaneous requests from the same client are
  312. involved, messages are not guaranteed to be delivered to the same window that
  313. created them nor, in some cases, at all. Note that this is typically not a
  314. problem in most applications and will become a non-issue in HTML5, where each
  315. window/tab will have its own browsing context.
  316. Settings
  317. ========
  318. A few :ref:`settings<settings-messages>` give you control over message
  319. behavior:
  320. * :setting:`MESSAGE_LEVEL`
  321. * :setting:`MESSAGE_STORAGE`
  322. * :setting:`MESSAGE_TAGS`
  323. For backends that use cookies, the settings for the cookie are taken from
  324. the session cookie settings:
  325. * :setting:`SESSION_COOKIE_DOMAIN`
  326. * :setting:`SESSION_COOKIE_SECURE`
  327. * :setting:`SESSION_COOKIE_HTTPONLY`
  328. Testing
  329. =======
  330. This module offers a tailored test assertion method, for testing messages
  331. attached to an :class:`~.HttpResponse`.
  332. To benefit from this assertion, add ``MessagesTestMixin`` to the class
  333. hierarchy::
  334. from django.contrib.messages.test import MessagesTestMixin
  335. from django.test import TestCase
  336. class MsgTestCase(MessagesTestMixin, TestCase):
  337. pass
  338. Then, inherit from the ``MsgTestCase`` in your tests.
  339. .. module:: django.contrib.messages.test
  340. .. method:: MessagesTestMixin.assertMessages(response, expected_messages, ordered=True)
  341. Asserts that :mod:`~django.contrib.messages` added to the :class:`response
  342. <django.http.HttpResponse>` matches ``expected_messages``.
  343. ``expected_messages`` is a list of
  344. :class:`~django.contrib.messages.Message` objects.
  345. By default, the comparison is ordering dependent. You can disable this by
  346. setting the ``ordered`` argument to ``False``.