Messages Framework

Back

Loading concept...

📬 Django Messages Framework: Your App’s Friendly Messenger

Imagine you have a magical mailbox at home. Every time something important happens—like when you finish your homework or when mom says “dinner is ready!”—a little note appears in the mailbox. You check the mailbox, read the note, and then the note disappears. That’s exactly what Django’s Messages Framework does for your web app!


🎯 What You’ll Learn

  1. Messages System Basics – How the magical mailbox works
  2. Message Levels and Tags – Different colored envelopes for different news
  3. Adding and Displaying Messages – Writing notes and showing them to users

🏠 Part 1: Messages System Basics

The Story of the Friendly Postman

Think of Django’s messages system like a friendly postman who lives inside your app. When something happens (like a user logs in), you tell the postman: “Hey, deliver this good news!” The postman holds onto that message until the user sees their next page, then delivers it and walks away.

Why Do We Need This Mailbox?

Imagine you’re playing a game and you score a point. Wouldn’t it be nice to see “🎉 Great job! You scored!” on your screen? That’s what messages do—they tell users what just happened.

Real Life Examples:

  • User logs in → “Welcome back, friend!”
  • User saves their profile → “Profile saved successfully!”
  • Something goes wrong → “Oops! Please try again.”

How Does It Work?

graph TD A["User Does Something"] --> B["You Create a Message"] B --> C["Message Waits in Line"] C --> D["Next Page Loads"] D --> E["Message Appears!"] E --> F["Message Disappears"]

Setting Up Your Mailbox

Good news! Django already has the mailbox ready. Just check your settings.py:

INSTALLED_APPS = [
    # ... other apps
    'django.contrib.messages',
]

MIDDLEWARE = [
    # ... other middleware
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
]

That’s it! The mailbox is open for business.


🎨 Part 2: Message Levels and Tags

Different Envelopes for Different News

Just like mail can come in different colored envelopes:

  • 📘 Blue envelope = Just FYI (information)
  • 📗 Green envelope = Good news!
  • 📙 Yellow envelope = Heads up! (warning)
  • 📕 Red envelope = Uh oh! (error)

Django has 5 message levels:

Level Number What It Means Example
DEBUG 10 For developers only “Database query took 2ms”
INFO 20 Just so you know “You have 3 new notifications”
SUCCESS 25 Good news! “Profile saved!”
WARNING 30 Be careful! “Password expires in 3 days”
ERROR 40 Something broke “Could not save. Try again.”

Using Message Levels

from django.contrib import messages

# Just information (blue)
messages.info(request, 'You have 3 items in cart')

# Good news! (green)
messages.success(request, 'Order placed!')

# Heads up! (yellow)
messages.warning(request, 'Stock is running low')

# Uh oh! (red)
messages.error(request, 'Payment failed')

# For developers (hidden usually)
messages.debug(request, 'Query took 50ms')

Tags: Naming Your Envelopes

Each message level comes with a tag—a name you can use in your HTML to style it:

Level Default Tag
DEBUG debug
INFO info
SUCCESS success
WARNING warning
ERROR error

These tags become CSS classes, so you can make success messages green and error messages red!

Custom Tags: Your Own Stickers

Want to add extra labels? Easy!

messages.success(
    request,
    'Profile updated!',
    extra_tags='profile-update important'
)
# Tags will be: "success profile-update important"

📤 Part 3: Adding and Displaying Messages

Adding Messages (Writing the Notes)

You add messages in your views. It’s as simple as calling a function:

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

def save_profile(request):
    # ... save the profile ...

    # Tell the user it worked!
    messages.success(request, 'Profile saved!')

    # Send them somewhere
    return redirect('profile')

The Two Ways to Add Messages

Way 1: Use the shortcut functions (Easiest!)

messages.debug(request, 'Debug info')
messages.info(request, 'FYI')
messages.success(request, 'Yay!')
messages.warning(request, 'Careful!')
messages.error(request, 'Oops!')

Way 2: Use add_message directly (More control)

from django.contrib.messages import constants

messages.add_message(
    request,
    constants.SUCCESS,
    'Profile saved!'
)

Displaying Messages (Showing the Notes)

In your template, loop through the messages:

{% if messages %}
<div class="message-box">
  {% for message in messages %}
  <div class="alert alert-{{ message.tags }}">
    {{ message }}
  </div>
  {% endfor %}
</div>
{% endif %}

Making Messages Look Pretty

Add some CSS to style your messages:

.alert {
  padding: 10px;
  border-radius: 5px;
  margin: 5px 0;
}

.alert-success {
  background: #d4edda;
  color: #155724;
}

.alert-error {
  background: #f8d7da;
  color: #721c24;
}

.alert-warning {
  background: #fff3cd;
  color: #856404;
}

.alert-info {
  background: #d1ecf1;
  color: #0c5460;
}

Complete Example: Login View

Here’s how it all works together:

# views.py
from django.contrib import messages
from django.shortcuts import redirect, render

def login_view(request):
    if request.method == 'POST':
        username = request.POST['username']
        password = request.POST['password']

        user = authenticate(
            username=username,
            password=password
        )

        if user:
            login(request, user)
            messages.success(
                request,
                f'Welcome back, {username}!'
            )
            return redirect('home')
        else:
            messages.error(
                request,
                'Invalid username or password'
            )

    return render(request, 'login.html')
<!-- base.html -->
<!DOCTYPE html>
<html>
<body>
  <!-- Messages appear here -->
  {% if messages %}
    {% for msg in messages %}
    <div class="alert alert-{{ msg.tags }}">
      {{ msg }}
    </div>
    {% endfor %}
  {% endif %}

  <!-- Rest of your page -->
  {% block content %}{% endblock %}
</body>
</html>

Messages Are One-Time Only!

Here’s something magical: once a message is shown, it disappears forever. Django automatically removes it after the user sees it. No cleanup needed!

graph TD A["Message Created"] --> B["Stored in Session"] B --> C["Page Loads"] C --> D["Message Displayed"] D --> E["Message Deleted!"] E --> F["Next page load: No message"]

🎉 You Did It!

You now know how to:

  • ✅ Use Django’s built-in messaging system
  • ✅ Choose the right message level (success, error, warning, info)
  • ✅ Add messages in your views
  • ✅ Display messages beautifully in templates
  • ✅ Style messages with CSS using tags

Remember: Messages are like friendly notes that appear once, deliver their news, and then politely disappear. Your users will always know what’s happening in your app!


🧠 Quick Reference

# Import
from django.contrib import messages

# Add messages
messages.success(request, 'Yay!')
messages.error(request, 'Oops!')
messages.warning(request, 'Careful!')
messages.info(request, 'FYI')

# In template
{% for message in messages %}
  <div class="alert-{{ message.tags }}">
    {{ message }}
  </div>
{% endfor %}

Now go make your app talk to your users! 🚀

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.