pythondjangodjango-messages

Django order of message tags


I wonder if it is possible to change the order of the message tags of a django message with extra tags.

from django.contrib import messages
messages.success(request, 'success message', extra_tags='safe')

And in my template I use

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

With this the class of the div will be:

<div class="alert alert-safe success">

but I want to have the two tags switched, so that I can use the bootstrap class.

<div class="alert alert-success safe">

Is this possible?


Solution

  • The tags property is defined in the Message class and hardcodes the order. I think it would be tricky to change it.

    An alernative would be to use {{ message.level_tag }} and {{ message.extra_tags }} in your template instead of {{ message.tags }}.

    <div class="alert alert-{{ message.level_tag }} {{ message.extra_tags|default_if_none:'' }}">
    

    If you're not using the safe class in your CSS, you might be able to remove the {{ message.extra_tags|default_if_none:'' }} part.

    An alternative approach would be to use a method like mark_safe or format_html in the view:

    messages.success(request, mark_safe('success message'))
    

    Then you won't need to check message.extra_tags in the template:

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