← Back to Chapters

Displaying Flash Messages in Django

? Displaying Flash Messages in Django

? Quick Overview

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.

? Key Concepts

  • Messages are stored temporarily in sessions
  • Displayed on the next request
  • Automatically removed after rendering

? Syntax / Theory

Django’s messages framework allows attaching messages to a request inside views. These messages are then accessible in templates using the messages context variable.

? Code Examples

? View Code Example
# 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')

? Live Output / Explanation

Each message appears once on the redirected page and disappears automatically after rendering.

? Template Rendering

? View Code Example
{# Loop through flash messages #}
{% if messages %}
{% for message in messages %}
{{ message }}
{% endfor %} {% endif %}

? Interactive Styling Example

? View Code Example
/* 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;
}

? Live Simulator

Click the buttons below to simulate how Django messages appear in the browser.

(Messages appear here)

? Use Cases

  • Form submission feedback
  • Authentication messages
  • Warnings before critical actions

✅ Tips & Best Practices

  • Always redirect after setting messages
  • Use appropriate message levels
  • Keep messages short and clear

? Try It Yourself

  • Add flash messages to a login form
  • Customize message animations
  • Display messages at different layout positions