Django's built-in messages framework allows you to store simple messages in one request and retrieve them in another. This is useful for scenarios where you want to pass information between views, such as displaying success messages after a form submission.
Here are the basic steps to use Django's messages framework:
Add django.contrib.messages
to your INSTALLED_APPS
in settings.py
:
pythonINSTALLED_APPS = [
# ...
'django.contrib.messages',
# ...
]
Add django.contrib.messages.middleware.MessageMiddleware
to your MIDDLEWARE
setting:
pythonMIDDLEWARE = [
# ...
'django.contrib.messages.middleware.MessageMiddleware',
# ...
]
Include the messages template tag in your templates:
In your template, include the {% messages %}
template tag where you want to display the messages. For example:
html{% if messages %}
<ul class="messages">
{% for message in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
This will render the messages in an unordered list. The message.tags
attribute can be used to add CSS classes based on the message type (success, error, warning, etc.).
Add messages in your views:
In your views, you can use the messages
module to add messages. Here's an example:
pythonfrom django.contrib import messages
from django.shortcuts import render, redirect
def my_view(request):
# Your view logic here
# Add a success message
messages.success(request, 'Operation was successful!')
# Redirect to another page
return redirect('some_other_view')
There are several message types you can use, such as success
, info
, warning
, and error
. You can choose the appropriate type based on the nature of the message.
That's it! The messages framework will store the messages in a cookie or session and retrieve them in the next request. The template tag will then render the messages in your HTML.
Remember that the messages framework is designed to work with the Django session framework, so make sure that your views use the same session. If you're using the default session configuration, everything should work seamlessly.