当用户成功更新密码时,我正在为他们起草一个电子邮件模板。
我在模板中使用了 {{ autoescape off }} ,它是使用 render_to_string() 渲染的。
但是,电子邮件内容直接显示 HTML 尖括号,如下所示:
<小时/> 我使用的是 Django2.0,我的代码如下所示:Hi <span style='color:blue'>user! </span>
Your password is updated successfully!
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/