Brenton Cleeland

How I use Django's messages framework

Published on

Screenshot of four messages displayed on a webpage

This is just a quick post to share a few code snippets that I find useful when dealing with Django's messages framework.

Have you noticed that when you start a new Django project django.contrib.messages is included in your INSTALLED_APPS? This is Django's lightweight framework for showing one-time notifications to users.

"One-time" describes one off the messages framework's key features: once a message has been displayed to the user it will be dismissed and not displayed again. I use this all the time to display success and error messages to users in simple Django applications.

Out of the box, messages supports the five standard levels of criticality (similar to Python's logging framework): DEBUG, INFO, SUCCESS, WARNING, ERROR. The MESSAGE_LEVEL setting is used to specify the minimum level to display – by default Django will show INFO and above.

When processing a request you can add a message with a snippet like:

from django.contrib import messages

messages.add_message(request, messages.SUCCESS, "Rating created successfully.")

The required middleware (SessionMiddleware) and template context processor (django.contrib.messages.context_processors.messages) are also installed by default. This means that a messages variable it available in your template to access this message.

I insert this HTML snippet into by base template where I want messages to be shown:

{% if messages %}
  <ul class="messages">
    {% for message in messages %}
    <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
  </ul>
{% endif %}

It uses a basic semantic structure to output the messages. Turns out that even though I've been copying this snippet from project to project for the last few years, this is straight out of the documentation.

CSS classes will be used to change the style of the different message types. The colours below are from the open-color project.

.messages {
    list-style: none;
    margin: 1em 0 2em;
    padding: 0;
}

.messages li {
    padding: 1em;
    width: 100%;
    line-height: 2.0em;
}

.messages li.info, .messages li.debug {
    background-color: #d0ebff;
}

.messages li.success {
    background-color: #b2f2bb;
}

.message li.warning {
    background-color: #ffec99;
}

.messages li.error {
    background-color: #ffe3e3;
}

Combining these two snippets gives me a quick and easy way to give success and failure notifications to users. The CSS provides some basic styling that can be extended on a per-project basis with some additional global styles.