python - Django 双转义引号等

标签 python django

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

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/

相关文章:

python - 在 url 中组合多个 slug

python - django 模型字段的不同 setter 和 getter

Django 中的 Jquery : Which django apps should I look into?

python - 将数据帧转换为列表,groupby() 不起作用

python - 从 APScheduler 收集 future

python - 在 Python Pandas 中查找两列的交集 -> 字符串列表

python - 为什么 celery 在执行我的任务时会返回 KeyError?

python - 在 Django 1.7 中动态过滤 ListView CBV

python - 用下划线替换空格,但不是全部

Python - 获取多部分电子邮件的正文