有没有办法在一个基于类的视图中创建一个方法,该方法能够在调用时输出另一个基于类的视图的 HTML?
伪代码看起来像这样:
class View1(ListView):
def method(self, *args, **kwargs):
return # template.html output from View2
class View2(ListView):
...
# normal ListView
您不使用 django 视图来创建电子邮件的 html 正文。为此,您可以使用render_to_string
. 在此处阅读更多信息:
https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut
这是您可以使用的代码段:
from django.template.loader import get_template
from django.template.loader import render_to_string
from django.template import Context
from django.core.mail import EmailMultiAlternatives
def send_template_email(context, # variables for the templates
plain_text, # plain text template
html_part, # html template
subject, # the email subject
recipients, # a list of recipients
from_addr):
plaintext = get_template(plain_text)
html_part = get_template(html_part)
ctx = Context(context)
text_content = plaintext.render(ctx)
html_content = htmly.render(ctx)
msg = EmailMultiAlternatives(subject,text_content,from_addr,recipients)
msg.attach_alternative(html_content,"text/html")
msg.send(True)
从您的视图(或任何地方)调用它,如下所示:
plain_text = 'plain-text.txt'
html_part = 'html-email.html'
recipients = ['user@email.com']
from_addr = 'admin@domain.com'
subject = 'Your email'
variables = {'name': 'John Smith'}
send_template_email(variables,
plain_text,
html_part,
recipients,
from_addr,
subject)
plain-text.txt
并且html-email.html
应该在您TEMPLATE_DIRS
所在位置的某个地方,这些是普通的 django 模板,因此plain-text.txt
可以是:
Dear {{ name }},
All you bases are belong to us!
Love,
--
Robot Overload
和html-email.html
:
<p>Dear {{ name }},<br />
All your bases are belong to <strong>us!</strong>
</p>
<hr />
<p>Love,<br />Robot <em>Overlord</em></p>