Django Message Framework

  • The Django Message Framework is a powerful feature that allows you to store simple messages for the user across requests. It provides an easy way to display one-time notifications, success messages, error messages, and other types of messages to the user. These messages are typically used to provide feedback or information after certain actions, such as submitting a form or completing an operation.
Here's an example to illustrate how the Django Message Framework works:
  • Configure message framework in project's settings.py file:


    from django.contrib.messages import constants as messages

  • Include messages app in installed app array:


    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]

  • Include messages middleware in middleware array:

    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]

  • Include message template in Templates Array.


    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [TEMPLATES_DIR],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

  • Include Message Tags Array:


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

  • Let message framework configuration part is complete.
  • Lets use it.
  • views.py:


    from django.shortcuts import render
    from django.contrib import messages

    def handleHome(request):
        messages.success(request, 'Registration successful! You can now log in.')

        messages.set_level(request, 10)
        messages.debug(request, "SQL statements were executed.")
        messages.info(request, "Three credits remain in your account.")
        messages.warning(request, "Your account expires in three days.")
        messages.error(request, "Document deleted.")
        return render(request, "app/index.html")

  • templates/base.html


    {% load static %}
    <!DOCTYPE html>
    <html lang="en">

    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="{% static 'css/app/index.css' %}">
        <title>{% block title %}{% endblock %}</title>
    </head>

    <body>
        <header>
            <h1>My Website</h1>
        </header>

        <div id="content">
            {% block content %}
            {% endblock %}
        </div>

        <footer>
            &copy; 2023 My Website
        </footer>
    </body>

    </html>

  • templates/app/index.html


    {% extends "base.html" %}

    {% block title %}App - My Website{% endblock %}

    {% block content %}

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

    <h1>This is App</h1>

    {% endblock %}

  • static/css/app/index.css


    .alert-success {
        background-color: green;
        color: white;
        padding: 10px;
    }

    .alert-info {
        background-color: rgb(33, 166, 228);
        color: white;
        padding: 10px;
    }

    .alert-warning {
        background-color: rgb(221, 218, 8);
        color: black;
        padding: 10px;
    }

    .alert-danger {
        background-color: rgb(209, 71, 29);
        color: white;
        padding: 10px;
    }

    .alert-debug {
        background-color: rgb(80, 41, 26);
        color: white;
        padding: 10px;
    }

  • In the app page template, we check if there are any messages available using `{% if messages %}`. If there are messages, we loop through them using `{% for message in messages %}` and display each message using `{{ message }}`.
  • The message will be rendered as HTML with the appropriate CSS classes for the message type (in this case, `alert-success`), giving it a visually appealing appearance.
  • Note that you need to ensure that the `messages` context processor is enabled in your Django settings (`TEMPLATES` setting) for the message framework to work correctly.
  • The Django Message Framework provides other methods such as `messages.error()`, `messages.warning()`, and `messages.info()`, which can be used to add different types of messages. You can also customize the appearance of the messages in your CSS to match the styling of your application.
  • In Django, the messages.debug() method is part of the Django Message Framework and is used to add debug-level messages to the message queue. Debug messages are primarily intended for developers during the development and debugging process. They are not typically displayed to end users in production environments.
  • It's important to note that by default, the debug-level messages are not displayed. Django only displays messages with a higher level of severity, such as success, info, warning, and error. To enable the display of debug messages during development, you need to include the django.contrib.messages.middleware.MessageMiddleware middleware in your Django settings (MIDDLEWARE setting). Ensure that it's placed after the SessionMiddleware.
  • Remember to remove or disable the display of debug messages in production environments to prevent sensitive information from being exposed to end users.
  • Debug messages are useful for developers to output specific information, variable values, or debugging details during the development process, but they should be used with caution and removed or disabled in production environments to ensure the security and integrity of your application.

No comments:

Post a Comment