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.
The messages framework uses middleware to make any outstanding notifications for the user available in any view. By default, messages support five levels:
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
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
This view adds two messages to the logged-in user’s session, a greeting with the
INFO level and an alert with the
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.
You can access messages in your code using
get_messages() or directly within a template using the
messages value in the template context.
Add the following code to
templates/listing.html to display any messages to the user on the blog listing page.
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.