英文:
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 "kb/select_file_dialog.html" %}
{% if 'test'=='test' %}
<script>
var dialog = document.getElementById('my_modal_2');
dialog.showModal();
</script>
This gives me the error: KeyError: "'test'=='test'"
I have no idea why it thinks it's working with a dictionary. Without the problematic line {% if 'test'=='test' %}
the code runs fine.
答案1
得分: 2
问题在于变量和==
之间没有空格,因此模板解析器认为这是一个单一的标识符。是的,Django的模板解析器在我看来实现得不太好。
因此,您可以这样写:
<pre><code>{% if <b>'test'</b> == <b>'test'</b> %}
…
{% 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> %}
…
{% endif %}</code></pre>
> This one has even stumped Chat GPT.
That's not very surprising, unfortunately ChatGPT is very good in writing bogus answers.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论