Django — Messages
Message Framework
from django.contrib import messages
def my_view(request):
messages.success(request, 'Operation completed successfully!')
messages.error(request, 'Something went wrong.')
messages.warning(request, 'Please be careful.')
messages.info(request, 'Here is some information.')
return redirect('home')
Message Tags
| Tag | Description |
|---|---|
| success | Successful operation |
| error | Error occurred |
| warning | Warning message |
| info | Information |
| debug | Debug message |
Template Display
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }}">
{{ message }}
</div>
{% endfor %}
{% endif %}
Message Levels
from django.contrib.messages import constants as message_constants
# Optional: customize message levels
message_constants.DEBUG = 10
message_constants.INFO = 20
message_constants.SUCCESS = 25
message_constants.WARNING = 30
message_constants.ERROR = 40
Extra Tags
messages.success(request, 'Profile updated', extra_tags='profile')
Mini Practice
- Add success and error messages
- Display messages in templates
- Use different message levels
- Add extra tags
Up Next
Continue with Middleware — request/response processing.
Related Topics
Frequently Asked Questions about Messages
What is Messages in Django?
Messages is a fundamental concept in Django. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Messages?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Messages.
Why is Messages important in Django?
Messages is essential for Django development. Understanding this concept will help you write better code and solve real-world problems more effectively.