Django Tutorial Part 9: Using Flash Messages (Messages Framework)

Disclaimer: Your support helps keep JovialGuide running! Our content is reader-supported. This means if you click on some of our links, we may earn a commission.

There are times you would want to display one-time notification messages to your users after submitting a form. These one-time notification messages are called flash messages. In this complete beginners guide to Django – part 9, we will show you how to add one-time flash messages using the messages framework. This is a complete beginners guide to Django, so if you haven’t read part 8, then see Django tutorial series part 8: creating modelforms or see part 1 – introduction to Django to get started.

What is the Messages Framework?

When you successfully submit a form, the message that tells you the status of your form or action (if it was submitted or not, example: “Your details were submitted” or “Your details could not be submitted”) is called flash message. While developing web applications, there will be need to display one-time notifications or flash messages, for this reason, Django introduces messages framework.

Messages framework, usually called flash messages, is a one-time notification message that displays when you submit a form, when an action is successful, fails, pends, etc. It is called a one-time notification message because it displays once, and disappears or get removed when the page is reloaded. Flash messages are event-based, meaning that they are triggered by events or actions, like when a form is submitted.

Django - Flash Message Example

The usefulness of one-time notification messages, usually called flash messages is to display the status of the user action; if the action was completed or not. Without flash messages, users will not know the status of their events, like: if an item was added to the cart or not, content was deleted or not, payment was successful or not, etc.

Configuring the Messages Framework (Flash Messages)

The startproject command generates default project configuration files for you. One of these is the settings.py file, which houses the entire project configuration settings. The startproject command activates the messages framework by default, and houses it in the INSTALLED_APPS list:

INSTALLED_APPS = [
  ...
  'django.contrib.messages',
  ...
]

In the MIDDLEWARE list:

  ...
  'django.contrib.sessions.middleware.SessionMiddleware',
  'django.contrib.messages.middleware.MessageMiddleware',
  ...

And in context_processors, which is inside the TEMPLATES list:

TEMPLATES = [
  ...
  'context_processors': [
    ...
    'django.contrib.messages.context_processors.messages',
    ...
  ],
  ...
]

If you have all of these configurations enabled in the settings.py file of your Django project, then you are ready to use the messages framework (flash messages) in Django, if not then add them!

The Messages Framework Message Tags

The messages framework supports varieties of message tags that you can use to show flash messages based on different statuses – successful, failure, etc. The messages framework message tags are:

  • debug – for development-related messages
  • info – for information
  • success – for events or actions that were successful
  • warning – for semi-failure, or close to failure messages
  • error – for events or actions that were not successful (failed)

How to Use Flash Messages in Django (Messages Framework)

To use flash messages in Django (messages framework), we will:

Adding Flash Messages to Views

To use flash messages in Django views, we will start by importing messages. This will be used for adding flash messages in views.

Add the following import to the top of the blog views.py file:

from django.contrib import messages

After importing messages to the views file, we will add flash messages to the views that need them. Since the messages framework or flash messages are displayed when operations like create, update and delete are performed, it means that we will add flash messages to the:

Create views:

  • new_article views
  • new_category views

Update/edit views

  • edit_article views
  • edit_category views

Delete views

  • delete_article views and
  • delete_category views

Those are the views that need flash messages (messages framework). So, what we want to do now is to display flash messages when an article or category is: created, edited or deleted.

First, we will start by importing the messages framework. Add the following import to the top of your blog views:

from django.contrib import messages

Django messages framework can be used in two ways. Either:

  • messages.debug(request, ‘You are logged-in as {}’.format(request.user.username))
  • messages.info(request, ‘Learn Django from JovialGuide!’)
  • messages.success(request, ‘Form was submitted successfully!’)
  • messages.warning(request, ‘Please correct the form errors below!’)
  • messages.error(request, ‘An error occurred while submitting your form!’)

Or:

  • messages.add_message(request, messages.DEBUG, ‘You are logged-in as {}’.format(request.user.username))
  • messages.add_message(request, messages.INFO, ‘Learn Django from JovialGuide!’)
  • messages.add_message(request, messages.SUCCESS, ‘Form was submitted successfully!’)
  • messages.add_message(request, messages.WARNING, ‘Please correct the form errors below!’)
  • messages.add_message(request, messages.ERROR, ‘An error occurred while submitting your form!’)

For this complete beginners guide to Django, we will use the first method, but you can use any method or even both.

Adding Flash Messages to the Article & Category Create Views

New Article Views

We will start with the new_article function views. This views needs the success and the error message tags.

For success message, scroll down to the new_article views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Article was created successfully!')

Note:

  • Be sure it is above the redirect() function so that it can read the flash message before redirecting.

For error message, find:

else:
  article_form = ArticleForm(request.POST)

Add the following lines of code below it:

messages.error(request, 'There is an error, %s' %article_form.errors)
  • If there’s an error while submitted the form, we will display it using the article_form variable (remember we stored the ArticleForm() form into it). It exposes us to the form errors using the errors property. Like this: article_form.errors.

Note:

  • Remember to indent the code above to be inside the else block.
New Category Views

The new_category function views needs the success and the error message tags.

For success message, scroll down to the new_category views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Category was created successfully!')

Note:

  • Be sure it is above the redirect function so that it can read the flash message before redirecting.

For error message, find:

else:
  category_form = CategoryForm(request.POST)

Add the following lines of code below it:

messages.error(request, 'There is an error, %s' %category_form.errors)

Note:

  • Remember to indent the code above to be inside the else block.

Adding Flash Messages to the Article & Category Edit Views

Edit Article Views

The edit_article function views needs the success and the error message tags.

For success message, scroll down to the edit_article views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Article was updated successfully!')

Note:

  • Be sure it is above the redirect() function so that it can read the flash message before redirecting.

For error message, find:

else:
  article_form = ArticleForm(request.POST)

Add the following lines of code below it:

messages.error(request, 'There is an error, %s' %article_form.errors)

Note:

  • Remember to indent the code above to be inside the else block.
Edit Category Views

The edit_category function views needs the success and the error message tags.

For success message, scroll down to the edit_category views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Category was updated successfully!')

Note:

  • Be sure it is above the redirect() function so that it can read the flash message before redirecting.

For error message, find:

else:
  category_form = CategoryForm(request.POST)

Add the following lines of code below it:

messages.error(request, 'There is an error, %s' %category_form.errors)

Note:

  • Remember to indent the code above to be inside the else block.

Adding Flash Messages to the Article & Category Delete Views

Delete Article Views

The delete_article function views needs the success message tag alone, compare to the create and update view functions.

For success message, scroll down to the edit_article views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Article was deleted successfully!')

Note:

  • Be sure it is above the redirect() function so that it can read the flash message before redirecting.

Delete Category Views

Just like the delete_article views, the delete_category function views needs the success message tag alone.

For success message, scroll down to the edit_category views and locate the following code lines:

return redirect('homepage')

Add the following flash message code above it:

messages.success(request, 'Category was deleted successfully!')

Note:

  • Be sure it is above the redirect() function so that it can read the flash message before redirecting.
  • Make sure your code follows the right indentation

Adding Flash Messages to the Base Template

Since the beginning of this complete beginners guide to Django, we have been using Bootstrap, which is a very popular CSS framework for responsive and faster web design. So, for beautiful flash messages, we are using the Bootstrap’s alert component.

Since we have a base.html template which other templates inherit from, then we will add the flash message to it so that we will not have to copy and paste on all templates.

Here, we will use Bootstrap’s alert component to display our flash messages.

Open the blog’s base.html template and find the following code lines:

<div class="container mt-5">
  {% block content %}{% endblock %}
</div>

Add the following above it:

{% if messages %}
<div class="container mt-5">
  {% for message in messages %}
  <div class="alert {{ message.tags }} alert-dismissible fade show" role="alert">
    {{ message }}
    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
  </div>
  {% endfor %}
</div>
{% endif %}
  • We check if there’s any messages using Python’s if statement. If there’s a message, then we loop through each flash message.

Adding Message Tags in Settings (Optional)

This is the last step to using flash messages. This step requires you to update the settings.py file by adding Bootstrap alert classes to each Django message tag. This step is purely optional. However, if you are using the Bootstrap alert component like the section above, then we strongly recommend you use it for class referencing purpose. By following this section will make your flash messages beautiful.

We are using the Bootstrap alert component to style our flash messages, so let’s update the settings.py file to support Bootstrap alert component classes:

Open settings.py, add the following imports where other imports are:

from django.contrib.messages import constants as messages

After that, scroll to the bottom and add the following message tag configurations:

# MESSAGE_TAGS
MESSAGE_TAGS = {
  messages.DEBUG: 'alert-info',
  messages.INFO: 'alert-info',
  messages.SUCCESS: 'alert-success',
  messages.WARNING: 'alert-warning',
  messages.ERROR: 'alert-danger',
}

What the above message tag configuration does is to replace alert {{ message.tags }} with the correct message tag as defined above. This means that if the message tag is SUCCESS in the views, then when rendering in the template, it checks the MESSAGE_TAGS (in settings) then replaces alert {{ message.tags }} with the corresponding message tag (as defined above). For example: the messages.success message tag will produce alert alert-success Bootstrap class, messages.error will produce alert alert-danger Bootstrap class, etc.

The flash message won’t display until you trigger an action, like delete, update or create a new article or category.

Run your development server if it is not running:

python manage.py runserver

Visit your development server via 127.0.0.1:8000/ and create, update or delete any article or category to see the messages framework in action.

Django - Flash Message Example

Complete Beginners Guide to Django

In this complete beginners guide to Django, we have been able to cover part 1 – part 8. If you need to read them again, or have not read them yet, please see:

We hope this complete beginners guide to Django – adding flash messages using the messages framework (part 9) helped you learn how to use the messages framework in Django. This is a complete beginners guide to Django, so if you haven’t read part 8, then see Django tutorial series part 8: creating modelforms or see part 1 – introduction to Django to get started.

See other of our Django tutorials for more.

You Might Also Like

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Shares