I wanted to play around with messages in my Django-application. Unfortunately every messagetype seems to work as expected except the error message is not red.
My Code is very simple.
views.py
from django.contrib import messages
def generate_test(request):
messages.info(request, 'TEST')
messages.success(request, 'TEST')
messages.warning(request, 'TEST')
messages.error(request, 'TEST')
return render(request, 'test.html')
test.html
{% extends "base_generic3.html" %}
{% load static %}
{% block content %}
{% endblock %}
My base_generic3.html contains a lot of other content like jquery and bootstrap-4 integrations. But the below part is for displaying the message in bootstrap-4 style:
...
{% if messages %}
{% for message in messages %}
<div class="alert alert-{{ message.tags }} alert-dismissible text-center" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span>
</button>
<strong>{% if message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}Error{% else %}{{ message.tags|title }}{% endif %}!
</strong> {{ message }}
</div>
{% endfor %}
{% endif %}
...
The issue is that Django's default message tags do not match perfectly with Bootstrap's contextual classes. Bootstrap uses the contextual class danger
for the color red. You can add the MESSAGE_TAGS
setting to your settings.py
to apply the danger
tag to messages with the level messages.ERROR
.
To change the default tags for a message level (either built-in or custom), set the MESSAGE_TAGS setting to a dictionary containing the levels you wish to change. As this extends the default tags, you only need to provide tags for the levels you wish to override:
settings.py
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.ERROR: 'danger',
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With