By default, messages.success outputs class='success'
. Either I need to overwrite this, remove it or append my tags to it to meet my needs. I've been unsuccessful in finding a way to overwrite and append to it. Here I've attempted to use extra_tags
...
messages.success(request, '<a href="#">Item</a> Saved', extra_tags='html_safe alert alert-')
I've tried adding alert
before the {{ message.tags }}
.
{% if messages %}
<ul class='messages'>
{% for message in messages %}
<li{% if message.tags %} class='{{ message.tags }}' role='alert'{% endif %}>{% if 'html_safe' in message.tags %}{{ message|safe }}{% else %}{{ message }}{% endif %}</li>
{% endfor %}
</ul>
{% endif %}
class='alert alert-success'
<div class="alert alert-success" role="alert">
<strong>Well done!</strong> You successfully read this important alert message.
</div>
When all the code above is executed, the source code outputs the following. The only problem now is the space between alert-
and success
.
<ul class='messages'>
<li class='html_safe alert alert- success' role='alert'><a href="#">Item</a> Saved</li>
</ul>
<li class="html_safe alert alert-success" role="alert"><a href="#">Item</a> Saved</li>
I don't see why there is a reason to remove it. Unused CSS classes are not a terrible thing. Change it to:
messages.success(request, '<a href="#">Item</a> Saved', extra_tags='html_safe alert alert-success')
and don't worry about the extra success
class. Have you checked Django's source code for this? Sometimes it gives hints as to extra kwargs
that can be passed. The end result will be:
<li class="html_safe alert alert-success success" role="alert"><a href="#">Item</a> Saved</li>
It seems there are also ways to configure the default message tags.
For example, in your settings.py
:
from django.contrib.messages import constants as messages
MESSAGE_TAGS = {
messages.SUCCESS: 'alert alert-success',
}
But some Django projects and documentation may assume that the tag here is success
, the default, so only change this if you are confident it is what you need. Otherwise, just add the Bootstrap class as an extra tag. Really, you shouldn't override Django's default just to suit Bootstrap. Either change Bootstrap's success class during customization to success
, or just use both.
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