Basics of Django messages framework

Reading Time : ~ .

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
Django Custom Management Command Siva Chittamuru

In Django project, We could manage by executing some commands which could be invoked through the manage.py.

For example:
# Sync database
python manage.py syncdb

...

Continue Reading...
Django Raw Sql Queries Vamsi Popuri

When your model query API don't go well or you want more performance, you can use raw sql queries in django. The Django Object Relational ...

Continue Reading...
Querying with Django Q objects Dinesh Deshmukh

Querying with Django Q objects: Q object encapsulates a SQL expression in a Python object that can be used in database-related operations. Using Q objects ...

Continue Reading...

Subscribe To our news letter

Subscribe to our news letter to receive latest blog posts into your inbox. Please fill your email address in the below form.
*We don't provide your email contact details to any third parties