是否可以将视图生成的pdf附加到django中的电子邮件中?

时间:2017-02-24 02:59:04

标签: django email pdf

我正在使用this第三方应用来生成pdf。

在我看来,我有这个用于创建Pdf的代码:

class artwork_catalog(PDFTemplateView):
    template_name = "someapp/sometemplate.html"

    def get_context_data(self, **kwargs):
        return super(artwork_catalog, self).get_context_data(
            pagesize="A4",
            title="My Title" + datetime.datetime.now().strftime('%m/%Y'),
            artworks=ArtWork.objects.filter(public=True).order_by('year'),
            **kwargs
        )

我的观点有以下网址:

url(
        r"^mypdf.pdf$",
        artwork_catalog.as_view()
    ),

所以我可以在localhost:8000/mypdf.pdf访问我的Pdf。 现在我想将此Pdf作为附件发送给每封电子邮件。我创建了一个视图,但我无法将其用于工作:

def order_catalog(request):
    if request.method == 'POST':
        form = OrderCatalogForm(request.POST)
        if form.is_valid():
            subject = 'Test'
            from_email = 'Test@Test.com'
            message = 'TESTTESTTESTTEST'
            recipient = form.cleaned_data['email']
            pdf = artwork_catalog # here I'd like to insert my Pdf
            try:
                mail = EmailMessage(subject, message, from_email, [recipient])
                mail.attach("MyPdf.pdf", pdf, "application/pdf")
                mail.send()
            except:
                return HttpResponse('Error')
            return redirect('/somewhere/')
    else:
        form = OrderCatalogForm()
    return render(request, 'someapp/order_catalog.html', {'form': form})

任何提示?最好的问候曼努埃尔

1 个答案:

答案 0 :(得分:0)

如果您仍然对某个解决方案感兴趣,则可以使用easy_pdf.rendering.render_to_pdf

执行以下操作
from easy_pdf.rendering import render_to_pdf
...
pdf = render_to_pdf(
        'someapp/sometemplate.html',
        {
            'pagesize': "A4",
            'title': "My Title" + datetime.datetime.now().strftime('%m/%Y'),
            'artworks' ArtWork.objects.filter(public=True).order_by('year')
        }
)