Files
fundor333.com/content/post/2022/message-and-allert-with-django-and-boostrap/index.md
2025-01-27 00:11:12 +01:00

2.4 KiB

title, date, feature_link, feature_text, tags, slug, categories, description, meta, series
title date feature_link feature_text tags slug categories description meta series
Message and Allert With Django and Boostrap 2022-05-02T12:21:50+02:00 https://unsplash.com/photos/M7NajHCqZDM?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink Photo by Anita Jankovic on Unsplash
django
coding
boostrap
message-and-allert-with-django-and-boostrap
dev
fingerfood
How to use Django messages with Boostrap5
message
allert
Django tricks

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