Messaging a Logged-in User
00:00 Messaging a Logged-in User. Django includes a mechanism for notifying your users. This is tied to their authentication and can be used inside any authorized Django view.
00:13
The messages framework uses middleware to make any outstanding notifications for the user available in any view. By default, messages support five levels: DEBUG
, INFO
, SUCCESS
, WARNING
, and ERROR
.
00:31
The messages framework is used primarily for asynchronous communication with the user. For example, if a background job goes wrong, then you can inform the user by sending a message with the ERROR
level.
00:45
Unfortunately, there is no area in the admin for creating messages. They have to be created in code. To demonstrate this, add the following code to your core/views.py
.
01:28
This view adds two messages to the logged-in user’s session, a greeting with the INFO
level and an alert with the WARNING
level.
01:37
messages.add_message()
takes three parameters: the HttpRequest
object, the message level, and the message itself. To use messages.add_message()
, you need to register the view as a URL.
02:03
You can access messages in your code using get_messages()
or directly within a template using the messages
value in the template context.
02:12
Add the following code to templates/listing.html
to display any messages to the user on the blog listing page.
02:59
This code uses a list of messages
in the template context that’s put there by the middleware. If there are messages, then an HTML unordered list is created showing each of them. Visit the /add_messages/
URL to create some messages as seen onscreen here, and then go to the blog listing page at the root of the site to see them.
03:23 If you refresh the page, you’ll notice that the messages are gone. Django automatically recognizes the fact that the notifications have been viewed and removes them from the session.
Become a Member to join the conversation.