Django检查message.tags是否包含字符串始终返回false。

huangapple go评论94阅读模式
英文:

Django checking if message.tags contains string always return false

问题

在我的视图中,我已经设置了extra_tags,但是当我在模板中检查目标标签时,条件始终评估为false。

视图:

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

模板:

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

这导致生成以下HTML:

* success
* you can undo this

这是我期望的:

* success
* this has undo in tags

(1)

英文:

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, &quot;success&quot;)
messages.info(request, &quot;you can undo this&quot;, extra_tags=&quot;undo&quot;)

Template:

{% for message in messages %}
  {{ message.extra_tags }}
  &lt;li&gt;
  {% if &#39;undo&#39; in messages.extra_tags %}
    this has undo in tags
  {% else %}
    {{ message }}
  {% endif %}
  &lt;/li&gt;
{% 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.

答案1

得分: 2

你的条件似乎不正确。因为你正在迭代来自消息框架的每条消息,你需要检查message上的extra_tags而不是messages

所以,你的模板应该如下所示:

{% for message in messages %}
  {{ message.extra_tags }}
  <li>
  {% if 'undo' in message.extra_tags %}
    这个标签中有“undo”
  {% else %}
    {{ message }}
  {% endif %}
  </li>
{% endfor %}

请注意,在这里,我们正在检查当前正在迭代的message对象。

英文:

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 }}
  &lt;li&gt;
  {% if &#39;undo&#39; in message.extra_tags %}
    this has undo in tags
  {% else %}
    {{ message }}
  {% endif %}
  &lt;/li&gt;
{% endfor %}

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

huangapple
  • 本文由 发表于 2023年2月27日 19:28:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579880.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定