How to use Django Messages Framework

June 2, 2020, 1:06 p.m.

How to use Django Messages Framework

Last Modified: Sept. 14, 2020, 12:46 p.m.

Django web framework provides a built-in messages framework used to display flash messages or notifications to both authenticated and anonymous users. These notifications are stored in a request and displayed after user input or interaction.

Some ways of using the messages framework in Django is to notify users upon form submissions and login/logout requests.

The Django messages example used in this tutorial is added to a Django contact form, with either a Django success message or a Django error message called upon form submission.

If you would like to see the exact Django contact form example used and use the Django form template, visit Build a Django Contact Us Form

 

How to use messages in Django

To display alert messages in Django, (1) check that the settings are configured properly, (2) add a message to a view function, and (3) display the message in a template.

 

Check that Django messages are added to the settings

env > mysite > mysite > settings.py

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

MIDDLEWARE = [
        ...
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
        'django.contrib.messages.middleware.MessageMiddleware',
        ...
    ]

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

Django messages framework is enabled by default in settings.py. Check that these 4 lines of code are listed in the settings. 

The installed app provides the default message tags, the Django message middleware allows the message to be called before or after the view function runs, and the context processor in the templates allows the messages to be called within any template without a defined context in views.py.

 

Django messages.tags

messages.debug(request, '%s SQL statements were executed.' % count)
messages.info(request, 'Three credits remain in your account.')
messages.success(request, 'Profile details updated.')
messages.warning(request, 'Your account expires in three days.')
messages.error(request, 'Document deleted.')

By default, Django has five message tag options: debug, info, success, warning, and error. These Django messages tags will be called in the views function and can also be assigned custom CSS attributes.

As of right now, you do not need to add them to the settings.py file. We will discuss assigning Bootstrap alerts to each tag toward the end of the article. We need to finish the basic configurations first.

 


 

How to import messages in Django views

Django tags are used directly in the Django view.py file after the return redirect in a function. 

 

Add a Django success message

env > mysite > main > views.py

from django.shortcuts import render, redirect
from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.contrib import messages #import messages

# Create your views here.
def contact(request):
	if request.method == 'POST':
		form = ContactForm(request.POST)
		if form.is_valid():
			subject = "Website Inquiry" 
		    body = {
			'first_name': form.cleaned_data['first_name'], 
			'last_name': form.cleaned_data['last_name'], 
			'email': form.cleaned_data['email_address'], 
			'message':form.cleaned_data['message'], 
			}
			message = "\n".join(body.values())

			try:
				send_mail(subject, message, 'admin@example.com', ['admin@example.com']) 
			except BadHeaderError:
				return HttpResponse('Invalid header found.')
			messages.success(request, "Message sent." )
			return redirect ("main:homepage")
      
	form = ContactForm()
	return render(request, "main/contact.html", {'form':form})

Import messages from django.contrib at the top of the file then go to the view function where you wish to add the message(s). In this case, it's a contact view that needs a Django success message and a Django error message.

Add a success message just before the return redirect ("main:homepage") stating "Message sent."

 

Add a Django return error message 

env > mysite > main > views.py

from django.shortcuts import render, redirect
from .forms import ContactForm
from django.core.mail import send_mail, BadHeaderError
from django.http import HttpResponse
from django.contrib import messages #import messages

# Create your views here.
def contact(request):
	if request.method == 'POST':
		form = ContactForm(request.POST)
		if form.is_valid():
			subject = "Website Inquiry" 
		    body = {
			'first_name': form.cleaned_data['first_name'], 
			'last_name': form.cleaned_data['last_name'], 
			'email': form.cleaned_data['email_address'], 
			'message':form.cleaned_data['message'], 
			}
			message = "\n".join(body.values())

			try:
				send_mail(subject, message, 'admin@example.com', ['admin@example.com']) 
			except BadHeaderError:
				return HttpResponse('Invalid header found.')
			messages.success(request, "Message sent." )
			return redirect ("main:homepage")
		messages.error(request, "Error. Message not sent.")
      
	form = ContactForm()
	return render(request, "main/contact.html", {'form':form})

Then add a Django error message just after the redirect, outside of the if condition, stating the message was not sent because of an error. You can customize the text of these messages to say what you'd like. 

If you are interested in creating a contact form like the one in the function above, learn to build a Django contact form with an email backend.

 


 

Django messages in template

Django messages require Django template tags and some HTML code with a Django template to render correctly. If you do not want to use a separate HTML file, add the code listed below directly to another template. 

 

Create a Django messages HTML template

env > mysite > main > templates > main > includes  > (New File) messages.html

{% if messages %}
<ul class="messages">
    {% for message in messages %}
    <li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
    {% endfor %}
</ul>
{% endif %}

Go to the includes folder and create a new file called messages.html. The includes folder holds smaller code snippets that are included within other templates. If you are looking to have the code appear on multiple templates, we recommend creating this folder and file. 

 

Include messages in the header.html

env > mysite > main > templates > main > header.html

<!DOCTYPE html>
<html>
  <head>
    ...
  </head>
  <body>

    {% include 'main/includes/messages.html' %}
    
    ...
  </body>
</html>

Then go to the header.html, or the file of your choice, and include message.html using the Django Template Language. If you are unsure about using include or do not have a header.html file, learn more about the Django template extends and include tags.

 

Django form submit success message

Now when you submit the form, you will be redirected to the homepage and an alert will appear stating "Message sent."

Django messages

 


 

Django + Bootstrap

The functionality of the messages framework is working correctly but the message itself has no CSS. Let's use Django with Bootstrap 4 to style the Django messages with Bootstrap alerts. Used together, Django and Bootstrap create messages and flash alerts with both style and functionality.

 

Django alert message in Bootstrap

All bootstrap alerts

Each Bootstrap alert color can be associated with a different Django message tag.

 

How to use Bootstrap in Django

env > mysite > main > templates > main > header.html

<!DOCTYPE html>
<html>
	<head>
    	<!-- Required meta tags -->
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
    	<!--Bootstrap CSS-->
    	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
  	</head>
  	<body>
        {% include 'main/includes/messages.html' %}

		{% block content %}
	
		{% endblock %}	


	 	<!-- Optional Javascript -->
	    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
	    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
	    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
  	</body>
</html>

Go to the Django header template and make sure you include the necessary Bootstrap CDNs in the head and body elements if you haven't already. If you are unsure how to add Bootstrap to a Django header template, visit How to use the Extends and Include Django Template Tags

 

Connect Bootstrap alerts to Django message tags

env > mysite > mysite > settings.py

"""
Django settings for mysite project.

Generated by 'django-admin startproject' using Django 3.0.8.

For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""

import os
from django.contrib.messages import constants as messages


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

Now, go back to the settings.py and add the Django messages import at the top of the file.

Then add MESSAGE_TAGS to the file. Assign each Django message tag a corresponding Bootstrap alert class attribute. This will apply the Bootstrap alerts CSS to the Django messages.

For example, if you are looking to show a Django error message in Bootstrap CSS, use the alert-danger. Or if you are looking to notify the user of important information, assign the Bootstrap info alert to the Django info message.

You can assign the same Bootstrap alert to multiple Django message tags.

Be sure to save the updated file before moving on to the next step.

 

Bootstrap alert message template

env > mysite > main > templates > main > includes  > messages.html

{% for message in messages %}
<div class="container-fluid p-0">
  <div class="alert {{ message.tags }} alert-dismissible" role="alert" >
    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
      <span aria-hidden="true">&times;</span>
    </button>
    {{ message }}
  </div>
</div>
{% endfor %}

The last thing needed is to update the messages template with Bootstrap class attributes. The code above places the alert across the entire width of the page.

The container-fluid and p-0 class attribute values place the alert across the entire width of the page. The Bootstrap class alert followed by the Django message tag given in the views provides the Bootstrap alerts CSS. 

Save the changes to the file then return to the browser and submit the form again. This time, a Bootstrap alert will appear displaying the message with the option to dismiss the alert.

Bootstrap alerts with Django messages

 


 

Django Login Template Bootstrap

Django + Bootstrap messages can be applied to other things besides contact forms. You can follow the Django Guide to User Registration, Login and Logout if you are looking to create a Django login form with Django login error messages and Django login success messages. 

Django User Login with Django Messages

 


 

If Django messages not showing

If your Django messages are not working correctly there are a couple of files and configurations you need to check.

  1. Check that all 4 lines of the Django messages settings are added to settings.py.
  2. Make sure messages are imported in views.py.
  3. Check that your view function is formatted correctly. The messages need to come after the return redirect, outside of the except and if statement, to work correctly. 

*If you are using AWS Cloud9 your Django messages may not appear until after you deploy.


0
Subscribe now

Subscribe to stay current on our latest articles and promos





Post a Comment
Join the community

0 Comments