The messages framework lets you store short, one-time notifications (like “Your profile was updated!”) that are
shown to users after an action. These may be for:
A successful form submission
A failed login attempt
A warning or error
They're stored temporarily (in the session or request) and automatically cleared once displayed.
Enabling Messages
Django's message framework is included by default, so you just need to confirm these apps and middleware are in
your settings.py:
INSTALLED_APPS = [
'django.contrib.messages',
# other apps...
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# other middleware...
]
You can overwrite the default values like so:
from django.contrib.messages import constants as message_constants
MESSAGE_TAGS = {
message_constants.DEBUG: 'debug',
message_constants.INFO: 'info',
message_constants.SUCCESS: 'success',
message_constants.WARNING: 'warning',
message_constants.ERROR: 'error',
}
You can even make custom ones like:
message_constants.SUCCESS: 'green-toast'
Including Messages in your Views
To access messages in your views, first import Django's message system at the top of the file and then add
your messages like so:
from django.shortcuts import redirect, render
from django.contrib import messages
def profile_update(request):
# some logic here...
messages.success(request, "Your profile has been updated successfully!")
return redirect('profile')
Message Levels
Level
Method
Purpose
Debug
messages.debug()
For developers (rarely shown to users)
Info
messages.info()
General info (“You're now logged in.”)
Success
messages.success()
Success messages
Warning
messages.warning()
Cautionary messages
Error
messages.error()
Error messages such as "Invalid password."
Display Messages in your Templates
Add this block (usually in base.html, right under the navbar or header). This loops through any queued messages
and displays them with classes depending on their level tags (e.g. alert-success, alert-warning).
{% if messages %}
<div class="messages">
{% for message in messages %}
<div class="alert
{% if message.tags %}alert-}} message.tags }}{% endif %}">
{{ message }}
</div>
{% endfor %}
</div>
{% endif %}
Django Message
Bootstrap Class
success
alert-success
info
alert-info
warning
alert-warning
error
alert-danger
If you use a CSS framework with different naming conventions (like Tailwind), you can override Django's default
tag mappings in the settings.py file. Shown above in the
Enabling Messages
section.
Style Messages
If you're using Bootstrap, Django's default tags match up nicely.