Messages Framework in Django


  • The Messages Framework is located at django.contrib.messages and it is included in the default INSTALLED_APPS list of settings.py file when we create new projects using python manage.py startproject. 
  • The messages framework provides a simple way to add messages to users.
  • settings file contains a middleware named django.contrib.messages.middleware. MessageMiddleware in the MIDDLEWARE settings.
  • Messages are stored in a cookie by default, and they are displayed in the next request from the user. 
  • The messages framework in your views by importing the messages module and adding new messages with simple shortcuts, as follows:

            from django.contrib import messages

            messages.error(request, 'Something Went Wrong Here....!')

  • Create new messages using the add_message() method or any of the following shortcut methods:
    • success(): Success messages to be displayed after an action has been successful
    • info(): Informational messages 
    • warning(): Something has not yet failed but may fail imminently
    • error(): An action was not successful or something failed
    • debug(): Debug messages that will be removed or ignored in a production environment
  • The messages framework includes the context processor django.contrib.messages.context_processors.messages, which adds a messages variable to the request context. 
  • You can find it in the context_processors list of the TEMPLATES setting of your project. You can use the messages variable in your templates to display all existing messages to the user.
  • A context processor is a Python function that takes the request object as an argument and returns a dictionary that gets added to the request context.

Comments

Post a Comment

Popular posts from this blog

Internationalization (Language Setting) in Django

reverse_lazy() Method in Django

CharFilter in Django