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