Django Messages Framework

The previous post made use of the Django messages framework to display a one-time message after an HTTP redirect.

Using the messages framework is simple. First, as explained in the docs, adjust your settings file:

  • ‘django.contrib.messages’ is in INSTALLED_APPS
  • MIDDLEWARE_CLASSES contains ‘django.contrib.sessions.middleware.SessionMiddleware’ and ‘django.contrib.messages.middleware.MessageMiddleware’
  • TEMPLATE_CONTEXT_PROCESSORS contains ‘django.contrib.messages.context_processors.messages’

You can now use the framework in a view:

from django.contrib import messages
# within a view method
messages.add_message(request, messages.INFO, 'This message will appear after the redirect!')

view raw

hosted with ❤ by GitHub

And display it within a template:

{% if messages %}
<div class="notice">
{% for message in messages %}
{{ message }}
{% endfor %}
{% endif %}

view raw


hosted with ❤ by GitHub

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s