How to Setup and Use Messages in Django

Use the messages feature in Django to make our users more confident and comfortable when using our application

Picture of Nsikak Imoh, author of Macsika Blog
White background with the text How to Setup and Use Messages in Django
White background with the text How to Setup and Use Messages in Django

This post is part of the tutorial series titled Learn to Use Django with FastAPI Frameworks

Table of Content

Django messages provide a way of keeping the users of your application up to date with what is going on. By communicating when business logic is loading, when there's some background activity processing, and the outcome of a processed logic.

This communication makes a huge difference in the user experience, as it keeps the user informed when the application changes state.

For example, let's say a user clicks a button to save a form, and nothing happens, no alert or indication, nothing. This leaves the user wondering if the provided information in the form is saved or not. What happens next? The user most times reacts by clicking multiple times and sometimes abandoning the application for an alternative if it isn't a mandatory activity they intended to accomplish.

Here's how you can leverage the messages feature in Django to make our users more confident and comfortable when using our application, thereby improving the user experience.

Set Up Messages in Django

By default, when we create a new Django project, the messages framework is already installed.

As long as you did not alter anything in the settings regarding the messages framework, you are welcome to skip to the next section.

Otherwise, here is how you can set up messages in Django:

  • INSTALLED_APPS

    • Add django.contrib.messages to your installed apps.
  • MIDDLEWARE or MIDDLEWARE_CLASSES

  • In older versions, add these middlewares

    • django.contrib.sessions.middleware.SessionMiddleware
    • django.contrib.messages.middleware.MessageMiddleware
  • TEMPLATES

    • Add django.contrib.messages.context_processors.messages to the context_processors of the templates in settings.

Levels and Tags of Messages in Django

There are various levels of messages in Django for different use cases.

The table below shows the various levels of messages, their use case, and CSS classes:

ConstantLevelTag (CSS Class)Use case
DEBUG10debugUsed for development-related messages that will be ignored or removed in a production deployment
INFO20infoUsed to provide informational messages for the user
SUCCESS25successUsed to indicate that the outcome of processing or action was successful
WARNING30warningUsed to indicate that a failure did not occur but may be imminent
ERROR40errorUsed to indicate that the outcome of processing or action was not successful or some other failure occurred

Django will only display messages with a level greater than 20 (INFO) by default. If you want to display DEBUG messages:

In settings.py, add the code below

from django.contrib.messages import constants as message_constants
MESSAGE_LEVEL = message_constants.DEBUG
Highlighted code sample.

If you encounter a circular import issue, you can add the constant value directly:

MESSAGE_LEVEL = 10  # DEBUG
Highlighted code sample.

How to Use Messages in Django

There are two ways you can use Messages in Django.

1. Built-in Method

This method is recommended if you are using the built-in message levels.
The various built-in methods are:

messages.debug(request, 'Total records updated {0}'.format(count))
messages.info(request, 'Improve your profile today!')
messages.success(request, 'Your password was updated successfully!')
messages.warning(request, 'Please correct the error below.')
messages.error(request, 'An unexpected error occurred.')
Highlighted code sample.
  1. In your views views.py
from django.contrib import messages

@login_required
def password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            update_session_auth_hash(request, form.user)
            messages.success(request, 'Your password was updated successfully!')  # <-
            return redirect('settings:password')
        else:
            messages.warning(request, 'Please correct the error below.')  # <-
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'profiles/change_password.html', {'form': form})
Highlighted code sample.
  1. In the template:
{% if messages %}
  <ul class="messages">
    {% for message in messages %}
      <li class="{{ message.tags }}">{{ message }}</li>
    {% endfor %}
  </ul>
{% endif %}
Highlighted code sample.
  • To add a success message to the example above, we can do something like this:
<ul class="messages">
  <li class="success">Your password was updated successfully!</li>
</ul>
Highlighted code sample.
  • You can also pass extra tags to the message:
messages.success(request, 'Your password was updated successfully!', extra_tags='alert')
Highlighted code sample.

Output:

<ul class="messages">
  <li class="success alert">Your password was updated successfully!</li>
</ul>
Highlighted code sample.

2. Custom Method

This method is useful in defining a custom level:

messages.add_message(request, messages.DEBUG, 'Total records updated {0}'.format(count))
messages.add_message(request, messages.INFO, 'Improve your profile today!')

CRITICAL = 50
messages.add_message(request, CRITICAL, 'A very serious error ocurred.')
Highlighted code sample.

Extra Snippet for Message You Can Adopt in Your Django Project

messages.html

{% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible" role="alert">
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message }}
  </div>
{% endfor %}
Highlighted code sample.

settings.py

from django.contrib.messages import constants as messages

MESSAGE_TAGS = {
    messages.DEBUG: 'alert-info',
    messages.INFO: 'alert-info',
    messages.SUCCESS: 'alert-success',
    messages.WARNING: 'alert-warning',
    messages.ERROR: 'alert-danger',
}
Highlighted code sample.

And then to use it, add messages.html to your base.html template:

base.html

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Simple is Better Than Complex</title>
  </head>
  <body>
    {% include 'partials/header.html' %}
    <main>
      <div class="container">
        {% include 'partials/messages.html' %}
        {% block content %}
        {% endblock %}
      </div>
    </main>
    {% include 'partials/footer.html' %}
  </body>
</html>
Highlighted code sample.

Wrap Off

Django messages provide a way of keeping the users of your application up to date with what is going on. By communicating the outcome of an action. It makes a huge difference in the user experience, as it keeps the user informed when the application changes state.

If you learned from this tutorial, or it helped you in any way, please consider sharing and subscribing to our newsletter.

Please share this post and for more insightful posts on business, technology, engineering, history, and marketing, subscribe to our newsletter.

Get the Complete Code of Django and FastAPI Combo Tutorials on Github.

Connect with me.

Need an engineer on your team to grease an idea, build a great product, grow a business or just sip tea and share a laugh?