Fundor 333's personal space on the web



Message and Allert With Django and Boostrap




Reading time 2 minutes
Word count 238
2022-05-02 12:21:50

Sometime you need to send an allert/message from your Django project to the user, like a popup or a gui message for an user interaction (“Sent the mail”, “Done the task”, …) and you want to make it with style (Boostrap in this case).

So this is my code.

Basic setup settings.py

Check if in the settings you have:

  • django.contrib.messages is in INSTALLED_APPS
  • django.contrib.sessions.middleware.SessionMiddleware and django.contrib.messages.middleware.MessageMiddleware are in MIDDLEWARE
  • The context_processors option of the DjangoTemplates backend defined in your TEMPLATES setting contains django.contrib.messages.context_processors.messages

This is the standard configuration for django messages 1 and we need to add some config for Boostrap.

We need to add the config for the class css for mapping the Boostrap allert with the Django messages. You can also add more messages level if you need.

from django.contrib.messages import constants as messages

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

Adding a Template

We need some html for the templates. I wrote this code and add in the top part of all my pages so I can show messages everywhere in my project

{% for message in messages %}
  <div class="container-fluid p-0">
    <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert">
      {{ message }}
  <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
  </div>
{% endfor %}

This fragment use Boostrap5 allerts2 but you can use your favorite CSS framework for your code

If you liked this article,

please share it on

or webmention it