Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Altering the default Django messages tag

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...

views.py

messages.success(request, '<a href="#">Item</a> Saved', extra_tags='html_safe alert alert-')

detail.html

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 %}

Bootstrap Alerts expects class='alert alert-success'

<div class="alert alert-success" role="alert">
    <strong>Well done!</strong> You successfully read this important alert message.
</div>

HTML page source result

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>

End Goal! - Can anyone see a hacky or proper workaround here?

<li class="html_safe alert alert-success" role="alert"><a href="#">Item</a> Saved</li>
like image 754
Alex Legg Avatar asked Apr 27 '16 19:04

Alex Legg


1 Answers

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.

like image 182
Jamie Counsell Avatar answered Sep 27 '22 15:09

Jamie Counsell