Basics of Django messages framework

In any web application, we need to display notification messages to the end user after processing a form or some other types of his requests. To make this messaging system simple, Django provided full support to cookie and session based messaging for both anonymous and authenticated users.

This messages framework is capable of storing messages in one request and retrieving those messages in the subsequent request. Every message has a tag based on its priority(info,warning and error).

Enabling Django messages:

-> we need to put 'django.contrib.messages' in INSTALLED_APPS.

-> MIDDLEWARE_CLASSES should contains 'django.contrib.sessions.middleware.SessionMiddleware' and 'django.contrib.messages.middleware.MessageMiddleware'.

-> The 'context_processors' option of the DjangoTemplates backend defined in your TEMPLATES setting contains 'django.contrib.messages.context_processors.messages'.

 storage.fallback.FallbackStorage is the default storage class.if you want, you can select another storage class by setting MESSAGE_STORAGE to its full import path, for example

MESSAGE_STORAGE = 'django.contrib.messages.storage.cookie.CookieStorage'

To write your own storage class, subclass the BaseStorage class in django.contrib.messages.storage.base and implement the _get and _store methods.

Add messages:

add_message(request, level, message, extra_tags='', fail_silently=False)

from django.contrib import messages
messages.add_message(request, messages.INFO, 'Hello world.')

 

Some shortcut methods to add messages with commonly used 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.')

 

Display Messages in Temaplates :

{% if messages %}
<ul>
   {% for message in messages %}
	   <li>{{ message }}</li>
   {% endfor %}
</ul>
{% endif %}

The context processor also provides a DEFAULT_MESSAGE_LEVELS variable which is a mapping of the message level names to their numeric value:

{% if messages %}
<ul>
   {% for message in messages %}
	<li>
	   {% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Important: {% endif %}
	      {{ message }}
       {% endfor %}
	</li>
</ul>
{% endif %}

Get messages outside Templates:

from django.contrib.messages import get_messages>

storage = get_messages(request)

for message in storage:

    do_something_with_the_message(message)

 

Elaborating django messages with example:

Models.py:

from django.db import models

class Student(models.Model):

    name = models.CharField(max_length=100)

    r_no = models.CharField(max_length=10)

 

forms.py

from django.forms import ModelForm

from myapp.models import Student

class StudentForm(ModelForm):

    class Meta:

        model = Student

        fields = ['name', 'r_no']

 

views.py

from myapp.forms import StudentForm

from django.contrib import messages

from django.shortcuts import render

def my_view(request):

    if request.method == "POST":

         student_form = StudentForm(request.POST)

     if student_form.is_valid():

          student_form.save()

          messages.success(request, 'Student created successfully.')

          return render(request,"template1.html")    

     else:

          messages.error(request, student_form.errors)

    students = Student.objects.all()  

    return render(request,"template2.html",{"students":students})

 

template1.html

{% if messages %}
<ul>
	{% for message in messages %}
	   <li>{{ message }}</li>
	{% endfor %}
</ul>
{% endif %}
<form action="." method="post">
    {% csrf_token %}
    <input name="name" type="text" />
    <input name="r_no" type="text" />
    <button type="submit">Submit</button>
</form>

template2.html

{% if messages %}
<ul>
	{% for message in messages %}
	   <li>{{ message }}</li>
	{% endfor %}
</ul>
{% endif %}
<h2>Student list
    By Posted On
SENIOR DEVELOPER at MICROPYRAMID

Need any Help in your Project?Let's Talk

Latest Comments
Related Articles
Google plus API integration with django Nikhila Mergu

Using GPlus integration, we can get the user verified email id, general information, friends in a less span of time, and user can also share ...

Continue Reading...
Integrating Gitlab in django project with gitlab api for gitlab authentication and access Nikhila Mergu

This is a simple way to integrate gitlab authentication in your django apps.

We can get user verified email id, general information, git lab URL ...

Continue Reading...
Using Python weasyprint generate HTML to PDF in django Swetha Naretla

WeasyPrint is to combine multiple pieces of information into an HTML template and then converting it to a PDF document.

Continue Reading...
open source packages

Subscribe To our news letter

Subscribe and Stay Updated about our Webinars, news and articles on Django, Python, Machine Learning, Amazon Web Services, DevOps, Salesforce, ReactJS, AngularJS, React Native.
* We don't provide your email contact details to any third parties