Message and Allert With Django and Boostrap
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
Comments
To reply to this post, you can send a Webmention or you can toot me at [email protected]
You mentioned this post on your site? Send a Webmention
This post is part of the Django Tricks series
- Django With Barcode and Qrcode
- Django Return Pdf With Reportlab
- Django List View With Show More
- Message and Allert With Django and Boostrap