Search code examples
djangojinja2

Django checking if message.tags contains string always return false


I have set extra_tags in my view, but when I check for the target tag in my template, the condition always evaluates to false.

View:

messages.success(request, "success")
messages.info(request, "you can undo this", extra_tags="undo")

Template:

{% for message in messages %}
  {{ message.extra_tags }}
  <li>
  {% if 'undo' in messages.extra_tags %}
    this has undo in tags
  {% else %}
    {{ message }}
  {% endif %}
  </li>
{% endfor %}

This result in this HTML:

* success
* you can undo this

This is what I expect

* success
* this has undo in tags

(1) I have confirmed that the "undo" tag is output from {{ message.extra_tags }}

(2) I have tried messages.tags instead of messages.extra_tags but neither method reaches the true branch in the if condition.


Solution

  • Your condition seems wrong. Since you're iterating over each message coming from the messages framework, you'll have to check the extra_tags on the message and not the messages.

    So, your template will become:

    {% for message in messages %}
      {{ message.extra_tags }}
      <li>
      {% if 'undo' in message.extra_tags %}
        this has undo in tags
      {% else %}
        {{ message }}
      {% endif %}
      </li>
    {% endfor %}
    

    Notice here, that we're checking the current message object that is being iterated on.