gpt4 book ai didi

python - Django 双转义引号等

转载 作者:行者123 更新时间:2023-12-01 06:19:36 25 4
gpt4 key购买 nike

我正在经历一些我认为有些奇怪的行为。具体来说,如果我有这样的字符串:

1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell

"A center for learning publication"--Cover.

被 Django 模板系统自动转义后,结果如下:

1984: Curriculum Unit
by Donald R. Hogue, Center for Learning, George Orwell

"A center for learning publication"--Cover.

问题似乎是应该变成 " 的“(引号)被转义两次,导致 &" 。这会导致格式看起来很奇怪。我使用的是 Django 1.0.2,所以它应该是最新的,(尽管我应该注意我正在使用 Ubuntu 9.04 包含的软件包 python-django),但这种行为似乎与预期行为相反。

我查看了 django.utils.html.py,其中包含实际功能:

def escape(html):

"""Returns the given HTML with ampersands, quotes and carets encoded."""

return mark_safe(force_unicode(html).replace('&','&amp;').replace('<','&lt;').replace('>', '&gt;').replace('"', '&quot;').replace("'",'&#39;'))

转义=allow_lazy(转义,unicode)

无论如何,看起来应该在其他任何事情之前转义 & ,这样就可以了。所以我怀疑它被调用了两次。有什么想法吗?

谢谢。

更新:我怀疑它可能与 Ubuntu 的 Django 有关,它列为“1.0.2-1”,所以我安装了“1.0.2-final”并遇到了问题同样的问题。

最佳答案

你不应该考虑在 1.0 中转义。如果您有模板

<html>
<body>
& == &amp; in HTML
</body>
</html>

在打印之前,它应该将 & 编码为 &

如果你有一个变量

<html>
<body>
{{ msg }}
</body>
</html>

def view(request) :
msg = "& == &amp; in HTML"

如果应该以同样的方式打印。

只有当您需要粘贴原始 html 时,您才需要自己进行编码。喜欢:

def view(request) :
msg = '<img src="http://example.com/pretty.jpg" />This picture is very pretty'

并在您的模板中

<html>
<body>
{{ msg|safe }}
</body>
</html>

关于python - Django 双转义引号等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1157725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com