Django Messages Framework
After a user performs an action — like saving a form, deleting a record, or logging in — it is good practice to show them a feedback message. For example: "Student added successfully!" or "Invalid login. Please try again." Django's built-in Messages Framework handles these temporary, one-time notifications cleanly and simply.
What is the Messages Framework?
The Messages Framework is a system in Django that lets you store a short notification in one view and display it in the next page after a redirect. The message is shown once and then automatically disappears — it is not stored permanently.
Example: Imagine you submit a job application at a reception desk and the receptionist says, "Your application has been received!" That message is for you, right now, just once — they will not keep repeating it every time you walk past. Django's messages work exactly the same way — show once, then gone.
Default Setup — Already Ready to Use
Django's messages framework is enabled by default in every new project. Check that these are present in settings.py (they are, by default):
INSTALLED_APPS = [
...
'django.contrib.messages', # <-- Must be present
...
]
MIDDLEWARE = [
...
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.messages.middleware.MessageMiddleware', # <-- Must be present
...
]
TEMPLATES = [{
...
'OPTIONS': {
'context_processors': [
...
'django.contrib.messages.context_processors.messages', # <-- Must be present
],
},
}]
Adding Messages in a View
Import the messages module and call messages.level(request, 'Your message here') before redirecting:
from django.shortcuts import render, redirect
from django.contrib import messages
from .forms import StudentForm
def add_student(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Student added successfully!') # <-- Add message
return redirect('student-list')
else:
messages.error(request, 'Please correct the errors below.') # <-- Error message
else:
form = StudentForm()
return render(request, 'add_student.html', {'form': form})
Message Levels — Types of Messages
Django provides five built-in message levels, each for a different type of notification:
messages.debug(request, 'text')— Development/debugging messages. Not shown in production by default.messages.info(request, 'text')— General informational messages. Example: "Your session will expire in 10 minutes."messages.success(request, 'text')— Positive confirmation messages. Example: "Profile updated successfully!"messages.warning(request, 'text')— Caution messages. Example: "Your password is about to expire."messages.error(request, 'text')— Error or failure messages. Example: "Login failed. Invalid credentials."
Example: Message levels are like the color of a traffic signal at an intersection. Green light (success) means all good and go ahead. Yellow (warning) means slow down and take note. Red (error) means stop, something went wrong.
Displaying Messages in a Template
Django automatically makes messages available in every template through the messages context variable. Add this block to your base.html so all pages can show messages:
{% if messages %}
{% for message in messages %}
<p>{{ message }}</p>
{% endfor %}
{% endif %}
To display each message with its level as a CSS class (so you can style success in green, error in red, etc.):
{% if messages %}
{% for message in messages %}
<div class="{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
The message.tags value returns the level name as a string — for example success, error, warning. You can use these as CSS class names to color-code your alerts.
Where to Place the Messages Block
The best place to add the messages display code is in your base.html template, right below the navigation bar and above the main content block. This way, every page in your website automatically shows messages without needing to add the code to each template:
{% load static %}
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My School{% endblock %}</title>
</head>
<body>
<nav>
<a href="/">Home</a> |
<a href="/students/">Students</a>
</nav>
<!-- Messages display block -->
{% if messages %}
{% for message in messages %}
<p>[{{ message.tags|upper }}] {{ message }}</p>
{% endfor %}
{% endif %}
<!-- Main page content -->
{% block content %}{% endblock %}
</body>
</html>
Using Messages with Authentication Views
Messages work great with login, logout, and registration events to give users clear feedback:
from django.contrib import messages
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
messages.success(request, 'Account created successfully! Please log in.')
return redirect('login')
else:
messages.error(request, 'Registration failed. Please check the form.')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form': form})
Adding Multiple Messages
You can add more than one message at the same time — all of them will be displayed on the next page:
messages.success(request, '5 students imported successfully.')
messages.warning(request, '2 records were skipped due to missing data.')
Customizing Message Storage
By default Django stores messages in the browser session. You can also change the storage backend in settings.py if needed:
# Default — stores in session
MESSAGE_STORAGE = 'django.contrib.messages.storage.session.SessionStorage'
# Stores in a browser cookie (useful if sessions are disabled)
MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'
# Tries cookie first, then falls back to session
MESSAGE_STORAGE = 'django.contrib.messages.storage.fallback.FallbackStorage'
Quick Recap
- The messages framework is enabled by default — no extra setup needed in new Django projects.
- Use
messages.success(),messages.error(),messages.warning(), andmessages.info()in views. - Always add messages before a
redirect()— the message is displayed on the next page. - Display messages in
base.htmlusing a{% for message in messages %}loop. - Use
message.tagsto apply CSS class names for visual styling. - Messages are one-time — they disappear after being displayed once.
