簡體   English   中英

Django CBV方法從不同的CBV輸出HTML

[英]Django CBV method to output HTML from a different CBV

有沒有辦法在一個基於類的視圖中創建一個方法,該方法能夠在調用時輸出另一個基於類的視圖的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.txthtml-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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM