【问题标题】:Django autoescape is not working in render_to_string(template)?Django autoescape 在 render_to_string(template) 中不起作用?
【发布时间】:2018-05-23 10:21:54
【问题描述】:

我正在为成功更新密码的用户起草电子邮件模板。

我在模板中使用了 {{ autoescape off }},通过 render_to_string() 进行渲染。

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

您好用户!

您的密码更新成功!


我正在使用 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() 时是否始终开启自动转义?

【问题讨论】:

  • 这与自动转义无关。这适用于从变量插入模板的 HTML,您没有这样做。

标签: python html django render-to-string


【解决方案1】:

这和autoescape无关,它是用来渲染变量的(它也是一个模板标签,所以你用{% autoescape off %},而不是{{ autoescape off }})。它在您当前的模板中什么都不做。

您的问题是您试图将 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
)

【讨论】:

  • 你是对的! send_mail() 只需要纯文本,这就是为什么我不能添加任何样式。也感谢您指出模板标签错误。 :P
猜你喜欢
  • 1970-01-01
  • 2011-02-10
  • 2019-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多