有没有办法在一个基于类的视图中创建一个方法,该方法能够在被调用时输出另一个基于类的视图的HTML?
psuedo代码看起来像这样:
class View1(ListView):
def method(self, *args, **kwargs):
return # template.html output from View2
class View2(ListView):
...
# normal ListView
答案 0 :(得分:1)
您不使用django视图来为电子邮件创建html正文。为此,您可以使用render_to_string
。在这里阅读更多相关信息:
https://docs.djangoproject.com/en/dev/ref/templates/api/#the-render-to-string-shortcut
答案 1 :(得分:1)
以下是您可以使用的代码段:
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>