python - Django 自动转义在 render_to_string(template) 中不起作用?

标签 python html django render-to-string

当用户成功更新密码时,我正在为他们起草一个电子邮件模板。

我在模板中使用了 {{ autoescape off }} ,它是使用 render_to_string() 渲染的。

但是,电子邮件内容直接显示 HTML 尖括号,如下所示:

Hi <span style='color:blue'>user! </span>

Your password is updated successfully!

<小时/> 我使用的是 Django2.0,我的代码如下所示:

views.py

from django.core.mail import send_mail
from django.template.loader import render_to_string

def sendmail(request, title)
    email_title = title
    email_content = render_to_string('template.html',{'username':request.user.username})
    recipient = request.user.email
    send_mail(
            email_title,
            email_content,
            'myemail@email.com',
            [recipient,],
            )

template.html

{{ autoescape off}}
Hi <span style='color:blue'>user! </span>
Your password is updated successfully!
{{ endautoescape }}

我的代码有什么问题吗?

否则,使用 render_to_string() 时自动转义是否始终开启?

最佳答案

这与 autoescape 无关,autoescape 是用于渲染变量的(它也是一个模板标签,所以你将它与 {% autoescape off %} 一起使用,而不是 {{ autoescape关闭}})。它在您当前的模板中根本没有执行任何操作。

您的问题是您尝试将 HTML 放入电子邮件的纯文本正文中。

send_mail需要纯文本消息正文。如果您想要 HTML 正文,则需要提供 html_message 参数:

send_mail(
    email_title,
    '',  # Empty plain text body - not recommended and you should supply a plain text alternative
    'myemail@email.com',
    [recipient,],
    html_message=email_content,  # This will render as HTML
)

关于python - Django 自动转义在 render_to_string(template) 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47726766/

相关文章:

html - 如何将内部标签定位在不同位置?

python - 从 django tastypie 中的多个表返回 json 输出

python - 当从 FastAPI 发送时流主体为满,当由请求接收时流主体为空

python - 为什么会超出范围?

html - 以右浮动元素为中心的元素

python - 如何包装第 3 方 Django 应用程序的 View

django - 将 Nginx 设置为 Apache 的反向代理与 Apache Event MPM 的反向代理

python - 如何在 Python 2.7 中检查字符串是(int 还是 float)

python - 我不断收到异常的语法错误

html - CSS下拉菜单子(monad)项定位