← Back to Chapters

Using Messages in Django Templates

? Using Messages in Django Templates

? Quick Overview

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.

? Key Concepts

  • Flash messages are temporary and shown only once
  • Messages persist across redirects
  • Each message has a level like success, error, or warning

? Syntax & Theory

Django automatically injects a messages variable into templates when the messages framework is enabled.

? Displaying Messages in Templates

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

? Styling Flash Messages

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

? Setting Messages in Views

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

? Live Output / Explanation

After redirecting, the messages appear once on the destination page and disappear automatically on refresh.

? Interactive Live Demo

Click the buttons below to simulate how Django injects messages into the template HTML:

 

? Interactive Idea

Trigger different messages by submitting forms with valid and invalid data to observe real-time feedback.

? Use Cases

  • Form submission confirmation
  • Error reporting
  • User action warnings

✅ Tips & Best Practices

  • Always use appropriate message levels
  • Style messages clearly for better UX
  • Keep messages concise and meaningful

? Try It Yourself

  • Add custom CSS animations to messages
  • Create reusable message components
  • Test messages across redirects