在我的项目中,我添加了一个通讯订阅功能。但是在试图使用此功能发送电子邮件时:
def send(request):
template_html = 'static/newsletter.html'
template_text = 'static/newsletter.txt'
newsletters = Newsletter.objects.filter(sent=False)
subject = _(u"Newsletter")
adr = NewsletterEmails.objects.all()
for a in adr:
for n in newsletters:
to = a.email
from_email = settings.DEFAULT_FROM_EMAIL
subject = _(u"Newsletter Fandrive")
text = get_template(template_text)
html = get_template(template_html)
d = { 'n': n,'email': to }
text_content = text.render(d)
html_content = html.render(d)
msg = EmailMultiAlternatives(subject, text_content, from_email, [to])
msg.attach_alternative(html_content, "text/html")
msg.send()
使用这些模板:
//text
=================== Newsletter - {{ n.date }} ============
==========================================================
{{ n.title }}
==========================================================
{{ n.text }}
==========================================================
//html
<html>
<head>
</head>
<body>
<div style="">
<div style="">
<h1 style="">{{ n.title }} - {{n.date}}</h1>
<p style="">
{{ n.text }}
</p>
</div>
</div>
</body>
</html>
并且模型:
class Newsletter(models.Model):
title = models.CharField("title", blank=False, max_length=50)
text = models.TextField("text", blank=False)
sent = models.BooleanField("sent", default=False)
data = models.DateTimeField("creation date", auto_now_add=True, blank=False)
class NewsletterEmails(models.Model):
email = models.EmailField(_(u"e-mail address"),)
我遇到了以下错误:
TemplateSyntaxError at /utils/newsletter_send/
Caught an exception while rendering: 'dict' object has no attribute 'autoescape'
错误发生在text_email模板中的{{ n.date }}位置。
我调试代码时发现我已经将newsletter对象正确传递到了模板中,并且调试上下文也正常:
context {'email': u'admin@domain.com', 'n': <Newsletter: Newsletter object>}
为什么会出现这种情况?从我对该错误的研究中得知,它与向模板渲染器发送空字典有关,但我的字典并不为空……