Flash messages are temporary notifications shown to users after actions like form submissions or updates. Django provides a built-in messages framework to display success, error, and warning messages efficiently.
Django’s messages framework allows attaching messages to a request inside views. These messages are then accessible in templates using the messages context variable.
# Import Django messages framework
from django.contrib import messages
from django.shortcuts import redirect
def my_view(request):
# Success message
messages.success(request,'The operation was successful!')
# Error message
messages.error(request,'Something went wrong, please try again.')
# Warning message
messages.warning(request,'Be careful, there might be some issues.')
return redirect('home')
Each message appears once on the redirected page and disappears automatically after rendering.
{# Loop through flash messages #}
{% if messages %}
{% for message in messages %}
{% endfor %} {% endif %}
/* Custom styles for flash messages */
.alert-success {
background-color:#d4edda;
color:#155724;
}
.alert-error {
background-color:#f8d7da;
color:#721c24;
}
.alert-warning {
background-color:#fff3cd;
color:#856404;
}
Click the buttons below to simulate how Django messages appear in the browser.