Lesson 49 of 60 – Django Messages Framework
82%

Django Messages Framework

Django provides a built-in messages framework that allows you to display temporary notifications to users after an action is performed.

Messages are useful for showing information such as successful form submissions, login status, warnings, errors, and other short notifications.

Note: Django messages are temporary notifications. They are commonly added in a view and displayed in a template during the next request.

1. What is the Django Messages Framework?

The Django messages framework provides a simple way to send notification messages from a view to a template.

For example, after creating a student record, you can display:

Student added successfully!

2. Why Use Messages?

Messages provide feedback to users after an action.

  • Show successful operations.
  • Display warning messages.
  • Display error messages.
  • Inform users about completed actions.
  • Provide temporary status information.

3. Messages Application

Django's messages framework is provided by:

django.contrib.messages

A standard Django project normally includes it in INSTALLED_APPS.

INSTALLED_APPS = [

    "django.contrib.messages",

]

4. Message Middleware

The messages framework requires its middleware to be enabled.

MIDDLEWARE = [

    "django.contrib.sessions.middleware.SessionMiddleware",

    "django.contrib.messages.middleware.MessageMiddleware",

]

The messages middleware works with Django's request and session handling.

5. Message Context Processor

Django normally includes a messages context processor in the template configuration.

TEMPLATES = [

    {
        "OPTIONS": {

            "context_processors": [

                "django.contrib.messages.context_processors.messages",

            ],

        },

    },

]

This makes messages available in templates.

6. Importing Messages

Import the messages module in your view.

from django.contrib import messages

You can then use the available message levels.

7. Adding a Success Message

Use messages.success() to add a successful-operation message.

messages.success(
    request,
    "Student added successfully!"
)

The message can then be displayed in a template.

8. Displaying Messages in a Template

Use the messages variable in the template.

{% if messages %}

    {% for message in messages %}

        <p>
            {{ message }}
        </p>

    {% endfor %}

{% endif %}

9. Success Message Example

from django.contrib import messages
from django.shortcuts import redirect

def add_student(request):

    # Save student

    messages.success(
        request,
        "Student added successfully!"
    )

    return redirect("students")

The message can be displayed after the redirect.

10. Info Messages

Use messages.info() for general informational messages.

messages.info(
    request,
    "Your profile was updated."
)

Information messages can tell users about the current status of an action.

11. Warning Messages

Use messages.warning() when you want to show a warning.

messages.warning(
    request,
    "Your subscription will expire soon."
)

12. Error Messages

Use messages.error() to display an error notification.

messages.error(
    request,
    "Unable to save the record."
)

Error messages can be used when an operation fails.

13. Debug Messages

Django also provides a debug message level.

messages.debug(
    request,
    "Debug information."
)

Debug messages can be useful during development, depending on the configured message level behavior.

14. Message Levels

Django provides several standard message levels.

Level Purpose
DEBUG Development/debug information.
INFO General information.
SUCCESS Successful operation.
WARNING Warning information.
ERROR Error notification.

15. Message Constants

Django provides constants for message levels.

from django.contrib.messages import (
    DEBUG,
    INFO,
    SUCCESS,
    WARNING,
    ERROR
)

These constants can be used when working with lower-level message APIs.

16. Using extra_tags

You can add extra CSS-related tags to a message.

messages.success(
    request,
    "Student saved!",
    extra_tags="student-success"
)

The extra tag can be used by the template or CSS framework to style the message.

17. Message Tags

Each message has a tag that represents its level.

{% for message in messages %}

    <p class="{{ message.tags }}">
        {{ message }}
    </p>

{% endfor %}

For example, a success message can have a success tag.

18. Bootstrap Alert Classes

Django message tags can be combined with Bootstrap alert classes.

{% for message in messages %}

<div class="alert alert-{{ message.tags }}">

    {{ message }}

</div>

{% endfor %}

This works well when your message tags correspond to Bootstrap alert classes.

19. Bootstrap Styling Example

A more controlled approach can map Django message levels to Bootstrap classes.

{% for message in messages %}

    {% if message.tags == "success" %}

        <div class="alert alert-success">
            {{ message }}
        </div>

    {% elif message.tags == "error" %}

        <div class="alert alert-danger">
            {{ message }}
        </div>

    {% elif message.tags == "warning" %}

        <div class="alert alert-warning">
            {{ message }}
        </div>

    {% else %}

        <div class="alert alert-info">
            {{ message }}
        </div>

    {% endif %}

{% endfor %}

20. Messages with Redirects

Messages are especially useful when redirecting after an operation.

messages.success(
    request,
    "Record updated successfully!"
)

return redirect("student_list")

The message can then be displayed on the redirected page.

21. Login Success Message

A login view can add a message after successful authentication.

from django.contrib import messages

login(request, user)

messages.success(
    request,
    "Login successful!"
)

return redirect("dashboard")

22. Logout Message

A logout view can also display a message.

logout(request)

messages.success(
    request,
    "You have been logged out."
)

return redirect("login")

This provides immediate feedback after logout.

23. Registration Success Message

A registration view can show a success message after creating a user.

User.objects.create_user(
    username=username,
    password=password
)

messages.success(
    request,
    "Account created successfully!"
)

return redirect("login")

24. Error Message Example

Messages can also be used when an operation fails.

if Student.objects.filter(
    email=email
).exists():

    messages.error(
        request,
        "Email already exists."
    )

    return redirect("add_student")

25. Complete Template Example

{% if messages %}

    {% for message in messages %}

        <div
            class="alert alert-{{ message.tags }}"
        >

            {{ message }}

        </div>

    {% endfor %}

{% endif %}

Place this code in a common template when you want messages to appear throughout the application.

26. Common Messages Mistakes

  • Forgetting to import messages.
  • Forgetting MessageMiddleware.
  • Removing the messages context processor.
  • Not including django.contrib.messages.
  • Adding messages but not displaying them in templates.
  • Using incorrect Bootstrap classes.
  • Forgetting to redirect or render the page where the message is expected.
  • Using message levels inconsistently.

27. Messages with Forms

Messages are useful after successful form submissions.

if form.is_valid():

    form.save()

    messages.success(
        request,
        "Form submitted successfully!"
    )

    return redirect("home")

This gives the user feedback without placing the message permanently in the database.

28. Complete Messages Workflow

User Performs Action
        ↓
Django View
        ↓
Operation Successful?
     ↙          ↘
   Yes           No
    ↓             ↓
success()      error()
    ↓             ↓
Redirect / Render
        ↓
Template
        ↓
Display Message

29. Complete View and Template Example

views.py

from django.contrib import messages
from django.shortcuts import redirect

def save_student(request):

    # Save student record

    messages.success(
        request,
        "Student saved successfully!"
    )

    return redirect("students")

students.html

{% if messages %}

    {% for message in messages %}

        <div
            class="alert alert-{{ message.tags }}"
        >

            {{ message }}

        </div>

    {% endfor %}

{% endif %}

30. Django Messages Summary

The Django messages framework provides a convenient way to display temporary notifications to users.

  • Import messages with from django.contrib import messages.
  • Use messages.success() for successful operations.
  • Use messages.info() for information.
  • Use messages.warning() for warnings.
  • Use messages.error() for errors.
  • Use the messages variable in templates.
  • Use message.tags for message-level styling.
  • Messages work especially well with redirects.
  • Bootstrap alert classes can be used to style messages.
  • Make sure the messages framework and middleware are configured.

📌 Key Points

  • Django messages display temporary notifications.
  • Use from django.contrib import messages.
  • Success, info, warning, error, and debug message levels are available.
  • Messages can be displayed using {% for message in messages %}.
  • message.tags can be used for styling.
  • Messages are useful after forms, login, logout, registration, and CRUD operations.
  • MessageMiddleware and the messages context processor are important configuration components.
  • Messages are commonly used before redirecting to another page.

🧠 Quick Quiz

Question: Which Django function is used to display a success message?