The Django messages framework allows you to display one-time notifications (flash messages) to users after actions like form submission, saving data, or encountering errors.
Django automatically injects a messages variable into templates when the messages framework is enabled.
{# Loop through all flash messages #}
{% if messages %}
{% for message in messages %}
{% endfor %} {% endif %}
/* Success message styling */
.alert-success {
background-color: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
/* Error message styling */
.alert-error {
background-color: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
/* Warning message styling */
.alert-warning {
background-color: #fff3cd;
color: #856404;
border: 1px solid #ffeeba;
}
# Adding flash messages inside a Django view
from django.contrib import messages
from django.shortcuts import redirect
def my_view(request):
messages.success(request, 'Your profile has been updated successfully!')
messages.error(request, 'An error occurred while updating your profile.')
messages.warning(request, 'You have unsaved changes.')
return redirect('profile')
After redirecting, the messages appear once on the destination page and disappear automatically on refresh.
Click the buttons below to simulate how Django injects messages into the template HTML:
Trigger different messages by submitting forms with valid and invalid data to observe real-time feedback.