django - 如何使用 msg.send() 在 django 的 html 电子邮件模板中传递用户名
问题描述
我是 Django 编码的新手。我目前正在研究 DRF Django Rest Framework 以及 API。我一直在尝试在用户注册后立即发送带有附件的 HTML 电子邮件模板。我已经实现了发送相同的功能,但我想将动态内容(如注册用户的电子邮件)从 views.py 传递到 HTML 电子邮件模板,但无法做到。我正在使用 msg.send()。
在 VIEWS.PY 中:
def attachment(request):
queryset = User.objects.all()
em=[]
h=[]
for star in queryset.iterator():
em.append(star.email)
print(em)
h=em[-1]
msg = mail.EmailMultiAlternatives(
subject = 'attachment',
body = 'Hi, Welcome!',
from_email = 'anushstella97@gmail.com',
to = [h],
connection = con
)
msg.attach_file('C:/Users/hp/Downloads/APIV1-master/APIV1-
master/polls/img.jpg')
msg_html = render_to_string('C:/Users/hp/Anaconda3/Lib/site-
packages/allauth/templates/account/email/email_confirmation_message.html'
, {"email": request.user.email})
msg.send()
return HttpResponse('<h1>Created</h1>')
在 HTML 模板中:
<p>Thanks for signing up! We're excited to have you as an early user.</p>
<p> Your registered email is : </p>
<p>
<strong> {{ email }} </strong></p>
解决方案
要呈现模板,您可以使用render_to_string
并from django.template.loader
传递上下文变量。
例如
from django.template.loader import render_to_string
html = render_to_string("account/email/email_confirmation_message.html", {"email": request.user.email})
在 email_confirmation_message.html 中:
Hi {{ email }},
...
推荐阅读
- html - HTML 页面中的异常/不需要的边距
- module - 在 Unqork 中,如何确保模块和工作流即使在 30 天后也不会被删除?
- angular - 是否可以在 OpenLayers 中结合 Modify 和 Draw 交互?
- flutter - 视频播放器在颤振 2.0 中崩溃(空安全)
- python - 为什么我在调用目标函数的值时遍历字典会导致 TypeError
- r - R问题:使用map将函数列表转换为函数名称的字符串列表
- azure - 如何自动更新自动化账户证书?
- flutter - 我正在将字体添加到我的颤振应用程序中,因为它无法正常工作
- odoo - Odoo 10 计划操作不起作用 odoo.service.server: WorkerCron
- firebase - Firebase 和 LinkedIn Auth 集成未知路由