Django模板错误:KeyError:“’test’ == ‘test’”(字符串 == 字符串)

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

Django Template Error: KeyError: "'test'=='test'" (string == string)

问题

这个问题甚至让Chat GPT都感到困惑,它认为我的代码没有任何问题。我将逐步解析我的代码,直到找出问题的根本原因,但鉴于问题非常奇怪,我想在这里记录下来。

我正在使用Django构建,并有一个Django模板。主模板调用了第二个模板,问题就发生在这第二个模板上:

{% include "kb/select_file_dialog.html" %}
{% if 'test'=='test' %}
  <script>
  var dialog = document.getElementById('my_modal_2');
      dialog.showModal();
  </script>

这给了我一个错误:KeyError: "'test'=='test'"

我不知道为什么它认为它在使用一个字典。如果将有问题的行{% if 'test'=='test' %}去掉,代码就能正常运行。

英文:

This one has even stumped Chat GPT who thinks there is nothing wrong with my code. I will slowly dissect my code till I get to the bottom of what is happening but given how bizarre it is, I wanted to document it here.

I am building using Django and have a Django template. The main template calls a second template and it's on that second template the issue is happening:

{% include &quot;kb/select_file_dialog.html&quot; %}
{% if &#39;test&#39;==&#39;test&#39; %}
  &lt;script&gt;
  var dialog = document.getElementById(&#39;my_modal_2&#39;);
      dialog.showModal();
  &lt;/script&gt;

This gives me the error: KeyError: &quot;&#39;test&#39;==&#39;test&#39;&quot;

I have no idea why it thinks it's working with a dictionary. Without the problematic line {% if &#39;test&#39;==&#39;test&#39; %} the code runs fine.

答案1

得分: 2

问题在于变量和==之间没有空格,因此模板解析器认为这是一个单一的标识符。是的,Django的模板解析器在我看来实现得不太好。

因此,您可以这样写:

<pre><code>{% if <b>'test'</b> == <b>'test'</b> %}
  &hellip;
{% endif %}</code></pre>

这个问题甚至让Chat GPT都感到困惑。

这并不令人惊讶,不幸的是,ChatGPT在编写虚假答案方面表现得非常出色。

英文:

The problem is that there are no spaces between the variables and ==, as a result the template parser things this is a single identifier. Yes, Django's template parser is not very well-implemented in my humble opinion.

You thus write:

<pre><code>{% if <b>'test' == 'test'</b> %}
&hellip;
{% endif %}</code></pre>

> This one has even stumped Chat GPT.

That's not very surprising, unfortunately ChatGPT is very good in writing bogus answers.

huangapple
  • 本文由 发表于 2023年7月28日 04:32:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/76783226.html
匿名

发表评论

匿名网友

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

确定