Debian Codegraph @

docs/ref/contrib/messages.txt

raw
1 ======================
2 The messages framework
3 ======================
4
5 .. module:: django.contrib.messages
6 :synopsis: Provides cookie- and session-based temporary message storage.
7
8 Quite commonly in web applications, you need to display a one-time
9 notification message (also known as "flash message") to the user after
10 processing a form or some other types of user input.
11
12 For this, Django provides full support for cookie- and session-based
13 messaging, for both anonymous and authenticated users. The messages framework
14 allows you to temporarily store messages in one request and retrieve them for
15 display in a subsequent request (usually the next one). Every message is
16 tagged with a specific ``level`` that determines its priority (e.g., ``info``,
17 ``warning``, or ``error``).
18
19 Enabling messages
20 =================
21
22 Messages are implemented through a :doc:`middleware </ref/middleware>`
23 class and corresponding :doc:`context processor </ref/templates/api>`.
24
25 The default ``settings.py`` created by ``django-admin startproject``
26 already contains all the settings required to enable message functionality:
27
28 * ``'django.contrib.messages'`` is in :setting:`INSTALLED_APPS`.
29
30 * :setting:`MIDDLEWARE` contains
31 ``'django.contrib.sessions.middleware.SessionMiddleware'`` and
32 ``'django.contrib.messages.middleware.MessageMiddleware'``.
33
34 The default :ref:`storage backend <message-storage-backends>` relies on
35 :doc:`sessions </topics/http/sessions>`. That's why ``SessionMiddleware``
36 must be enabled and appear before ``MessageMiddleware`` in
37 :setting:`MIDDLEWARE`.
38
39 * The ``'context_processors'`` option of the ``DjangoTemplates`` backend
40 defined in your :setting:`TEMPLATES` setting contains
41 ``'django.contrib.messages.context_processors.messages'``.
42
43 If you don't want to use messages, you can remove
44 ``'django.contrib.messages'`` from your :setting:`INSTALLED_APPS`, the
45 ``MessageMiddleware`` line from :setting:`MIDDLEWARE`, and the ``messages``
46 context processor from :setting:`TEMPLATES`.
47
48 Configuring the message engine
49 ==============================
50
51 .. _message-storage-backends:
52
53 Storage backends
54 ----------------
55
56 The messages framework can use different backends to store temporary messages.
57
58 Django provides three built-in storage classes in
59 :mod:`django.contrib.messages`:
60
61 .. class:: storage.session.SessionStorage
62
63 This class stores all messages inside of the request's session. Therefore
64 it requires Django's ``contrib.sessions`` application.
65
66 .. class:: storage.cookie.CookieStorage
67
68 This class stores the message data in a cookie (signed with a secret hash
69 to prevent manipulation) to persist notifications across requests. Old
70 messages are dropped if the cookie data size would exceed 2048 bytes.
71
72 .. class:: storage.fallback.FallbackStorage
73
74 This class first uses ``CookieStorage``, and falls back to using
75 ``SessionStorage`` for the messages that could not fit in a single cookie.
76 It also requires Django's ``contrib.sessions`` application.
77
78 This behavior avoids writing to the session whenever possible. It should
79 provide the best performance in the general case.
80
81 :class:`~django.contrib.messages.storage.fallback.FallbackStorage` is the
82 default storage class. If it isn't suitable to your needs, you can select
83 another storage class by setting :setting:`MESSAGE_STORAGE` to its full import
84 path, for example::
85
86 MESSAGE_STORAGE = "django.contrib.messages.storage.cookie.CookieStorage"
87
88 .. class:: storage.base.BaseStorage
89
90 To write your own storage class, subclass the ``BaseStorage`` class in
91 ``django.contrib.messages.storage.base`` and implement the ``_get`` and
92 ``_store`` methods.
93
94 .. _message-level:
95
96 Message levels
97 --------------
98
99 The messages framework is based on a configurable level architecture similar
100 to that of the Python logging module. Message levels allow you to group
101 messages by type so they can be filtered or displayed differently in views and
102 templates.
103
104 The built-in levels, which can be imported from ``django.contrib.messages``
105 directly, are:
106
107 =========== ========
108 Constant Purpose
109 =========== ========
110 ``DEBUG`` Development-related messages that will be ignored (or removed) in a production deployment
111 ``INFO`` Informational messages for the user
112 ``SUCCESS`` An action was successful, e.g. "Your profile was updated successfully"
113 ``WARNING`` A failure did not occur but may be imminent
114 ``ERROR`` An action was **not** successful or some other failure occurred
115 =========== ========
116
117 The :setting:`MESSAGE_LEVEL` setting can be used to change the minimum recorded level
118 (or it can be `changed per request`_). Attempts to add messages of a level less
119 than this will be ignored.
120
121 .. _`changed per request`: `Changing the minimum recorded level per-request`_
122
123 Message tags
124 ------------
125
126 Message tags are a string representation of the message level plus any
127 extra tags that were added directly in the view (see
128 `Adding extra message tags`_ below for more details). Tags are stored in a
129 string and are separated by spaces. Typically, message tags
130 are used as CSS classes to customize message style based on message type. By
131 default, each level has a single tag that's a lowercase version of its own
132 constant:
133
134 ============== ===========
135 Level Constant Tag
136 ============== ===========
137 ``DEBUG`` ``debug``
138 ``INFO`` ``info``
139 ``SUCCESS`` ``success``
140 ``WARNING`` ``warning``
141 ``ERROR`` ``error``
142 ============== ===========
143
144 To change the default tags for a message level (either built-in or custom),
145 set the :setting:`MESSAGE_TAGS` setting to a dictionary containing the levels
146 you wish to change. As this extends the default tags, you only need to provide
147 tags for the levels you wish to override::
148
149 from django.contrib.messages import constants as messages
150
151 MESSAGE_TAGS = {
152 messages.INFO: "",
153 50: "critical",
154 }
155
156 Using messages in views and templates
157 =====================================
158
159 .. function:: add_message(request, level, message, extra_tags='', fail_silently=False)
160
161 Adding a message
162 ----------------
163
164 To add a message, call::
165
166 from django.contrib import messages
167
168 messages.add_message(request, messages.INFO, "Hello world.")
169
170 Some shortcut methods provide a standard way to add messages with commonly
171 used tags (which are usually represented as HTML classes for the message)::
172
173 messages.debug(request, "%s SQL statements were executed." % count)
174 messages.info(request, "Three credits remain in your account.")
175 messages.success(request, "Profile details updated.")
176 messages.warning(request, "Your account expires in three days.")
177 messages.error(request, "Document deleted.")
178
179 .. _message-displaying:
180
181 Displaying messages
182 -------------------
183 .. function:: get_messages(request)
184
185 **In your template**, use something like:
186
187 .. code-block:: html+django
188
189 {% if messages %}
190 <ul class="messages">
191 {% for message in messages %}
192 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
193 {% endfor %}
194 </ul>
195 {% endif %}
196
197 If you're using the context processor, your template should be rendered with a
198 ``RequestContext``. Otherwise, ensure ``messages`` is available to
199 the template context.
200
201 Even if you know there is only one message, you should still iterate over the
202 ``messages`` sequence, because otherwise the message storage will not be
203 cleared for the next request.
204
205 The context processor also provides a ``DEFAULT_MESSAGE_LEVELS`` variable which
206 is a mapping of the message level names to their numeric value:
207
208 .. code-block:: html+django
209
210 {% if messages %}
211 <ul class="messages">
212 {% for message in messages %}
213 <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>
214 {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
215 {{ message }}
216 </li>
217 {% endfor %}
218 </ul>
219 {% endif %}
220
221 **Outside of templates**, you can use
222 :func:`~django.contrib.messages.get_messages`::
223
224 from django.contrib.messages import get_messages
225
226 storage = get_messages(request)
227 for message in storage:
228 do_something_with_the_message(message)
229
230 For instance, you can fetch all the messages to return them in a
231 :ref:`JSONResponseMixin <jsonresponsemixin-example>` instead of a
232 :class:`~django.views.generic.base.TemplateResponseMixin`.
233
234 :func:`~django.contrib.messages.get_messages` will return an
235 instance of the configured storage backend.
236
237
238 The ``Message`` class
239 ---------------------
240
241 .. class:: Message
242
243 When you loop over the list of messages in a template, what you get are
244 instances of the ``Message`` class. They have only a few attributes:
245
246 * ``message``: The actual text of the message.
247
248 * ``level``: An integer describing the type of the message (see the
249 `message levels`_ section above).
250
251 * ``tags``: A string combining all the message's tags (``extra_tags`` and
252 ``level_tag``) separated by spaces.
253
254 * ``extra_tags``: A string containing custom tags for this message,
255 separated by spaces. It's empty by default.
256
257 * ``level_tag``: The string representation of the level. By default, it's
258 the lowercase version of the name of the associated constant, but this
259 can be changed if you need by using the :setting:`MESSAGE_TAGS` setting.
260
261 Creating custom message levels
262 ------------------------------
263
264 Messages levels are nothing more than integers, so you can define your own
265 level constants and use them to create more customized user feedback, e.g.::
266
267 CRITICAL = 50
268
269
270 def my_view(request):
271 messages.add_message(request, CRITICAL, "A serious error occurred.")
272
273 When creating custom message levels you should be careful to avoid overloading
274 existing levels. The values for the built-in levels are:
275
276 .. _message-level-constants:
277
278 ============== =====
279 Level Constant Value
280 ============== =====
281 ``DEBUG`` 10
282 ``INFO`` 20
283 ``SUCCESS`` 25
284 ``WARNING`` 30
285 ``ERROR`` 40
286 ============== =====
287
288 If you need to identify the custom levels in your HTML or CSS, you need to
289 provide a mapping via the :setting:`MESSAGE_TAGS` setting.
290
291 .. note::
292 If you are creating a reusable application, it is recommended to use
293 only the built-in `message levels`_ and not rely on any custom levels.
294
295 Changing the minimum recorded level per-request
296 -----------------------------------------------
297
298 The minimum recorded level can be set per request via the ``set_level``
299 method::
300
301 from django.contrib import messages
302
303 # Change the messages level to ensure the debug message is added.
304 messages.set_level(request, messages.DEBUG)
305 messages.debug(request, "Test message...")
306
307 # In another request, record only messages with a level of WARNING and higher
308 messages.set_level(request, messages.WARNING)
309 messages.success(request, "Your profile was updated.") # ignored
310 messages.warning(request, "Your account is about to expire.") # recorded
311
312 # Set the messages level back to default.
313 messages.set_level(request, None)
314
315 Similarly, the current effective level can be retrieved with ``get_level``::
316
317 from django.contrib import messages
318
319 current_level = messages.get_level(request)
320
321 For more information on how the minimum recorded level functions, see
322 `Message levels`_ above.
323
324 Adding extra message tags
325 -------------------------
326
327 For more direct control over message tags, you can optionally provide a string
328 containing extra tags to any of the add methods::
329
330 messages.add_message(request, messages.INFO, "Over 9000!", extra_tags="dragonball")
331 messages.error(request, "Email box full", extra_tags="email")
332
333 Extra tags are added before the default tag for that level and are space
334 separated.
335
336 Failing silently when the message framework is disabled
337 -------------------------------------------------------
338
339 If you're writing a reusable app (or other piece of code) and want to include
340 messaging functionality, but don't want to require your users to enable it
341 if they don't want to, you may pass an additional keyword argument
342 ``fail_silently=True`` to any of the ``add_message`` family of methods. For
343 example::
344
345 messages.add_message(
346 request,
347 messages.SUCCESS,
348 "Profile details updated.",
349 fail_silently=True,
350 )
351 messages.info(request, "Hello world.", fail_silently=True)
352
353 .. note::
354 Setting ``fail_silently=True`` only hides the ``MessageFailure`` that would
355 otherwise occur when the messages framework disabled and one attempts to
356 use one of the ``add_message`` family of methods. It does not hide failures
357 that may occur for other reasons.
358
359 Adding messages in class-based views
360 ------------------------------------
361
362 .. class:: views.SuccessMessageMixin
363
364 Adds a success message attribute to
365 :class:`~django.views.generic.edit.FormView` based classes
366
367 .. method:: get_success_message(cleaned_data)
368
369 ``cleaned_data`` is the cleaned data from the form which is used for
370 string formatting
371
372 **Example views.py**::
373
374 from django.contrib.messages.views import SuccessMessageMixin
375 from django.views.generic.edit import CreateView
376 from myapp.models import Author
377
378
379 class AuthorCreateView(SuccessMessageMixin, CreateView):
380 model = Author
381 success_url = "/success/"
382 success_message = "%(name)s was created successfully"
383
384 The cleaned data from the ``form`` is available for string interpolation using
385 the ``%(field_name)s`` syntax. For ModelForms, if you need access to fields
386 from the saved ``object`` override the
387 :meth:`~django.contrib.messages.views.SuccessMessageMixin.get_success_message`
388 method.
389
390 **Example views.py for ModelForms**::
391
392 from django.contrib.messages.views import SuccessMessageMixin
393 from django.views.generic.edit import CreateView
394 from myapp.models import ComplicatedModel
395
396
397 class ComplicatedCreateView(SuccessMessageMixin, CreateView):
398 model = ComplicatedModel
399 success_url = "/success/"
400 success_message = "%(calculated_field)s was created successfully"
401
402 def get_success_message(self, cleaned_data):
403 return self.success_message % dict(
404 cleaned_data,
405 calculated_field=self.object.calculated_field,
406 )
407
408 Expiration of messages
409 ======================
410
411 The messages are marked to be cleared when the storage instance is iterated
412 (and cleared when the response is processed).
413
414 To avoid the messages being cleared, you can set the messages storage to
415 ``False`` after iterating::
416
417 storage = messages.get_messages(request)
418 for message in storage:
419 do_something_with(message)
420 storage.used = False
421
422 Behavior of parallel requests
423 =============================
424
425 Due to the way cookies (and hence sessions) work, **the behavior of any
426 backends that make use of cookies or sessions is undefined when the same
427 client makes multiple requests that set or get messages in parallel**. For
428 example, if a client initiates a request that creates a message in one window
429 (or tab) and then another that fetches any uniterated messages in another
430 window, before the first window redirects, the message may appear in the
431 second window instead of the first window where it may be expected.
432
433 In short, when multiple simultaneous requests from the same client are
434 involved, messages are not guaranteed to be delivered to the same window that
435 created them nor, in some cases, at all. Note that this is typically not a
436 problem in most applications and will become a non-issue in HTML5, where each
437 window/tab will have its own browsing context.
438
439 Settings
440 ========
441
442 A few :ref:`settings<settings-messages>` give you control over message
443 behavior:
444
445 * :setting:`MESSAGE_LEVEL`
446 * :setting:`MESSAGE_STORAGE`
447 * :setting:`MESSAGE_TAGS`
448
449 For backends that use cookies, the settings for the cookie are taken from
450 the session cookie settings:
451
452 * :setting:`SESSION_COOKIE_DOMAIN`
453 * :setting:`SESSION_COOKIE_SECURE`
454 * :setting:`SESSION_COOKIE_HTTPONLY`
455
456 Testing
457 =======
458
459 This module offers a tailored test assertion method, for testing messages
460 attached to an :class:`~.HttpResponse`.
461
462 To benefit from this assertion, add ``MessagesTestMixin`` to the class
463 hierarchy::
464
465 from django.contrib.messages.test import MessagesTestMixin
466 from django.test import TestCase
467
468
469 class MsgTestCase(MessagesTestMixin, TestCase):
470 pass
471
472 Then, inherit from the ``MsgTestCase`` in your tests.
473
474 .. module:: django.contrib.messages.test
475
476 .. method:: MessagesTestMixin.assertMessages(response, expected_messages, ordered=True)
477
478 Asserts that :mod:`~django.contrib.messages` added to the :class:`response
479 <django.http.HttpResponse>` matches ``expected_messages``.
480
481 ``expected_messages`` is a list of
482 :class:`~django.contrib.messages.Message` objects.
483
484 By default, the comparison is ordering dependent. You can disable this by
485 setting the ``ordered`` argument to ``False``.