5

嗨,我正在使用以下 2 个功能通过邮件即时创建和发送 pdf。我究竟做错了什么。(导出 pdf 功能在浏览器中显示时可以正常工作。)

我得到的错误是"TypeError: 'ContentFile' object does not support indexing"。我做错了什么?几乎所有这些代码都取自一些博客,所以我不知道它是如何工作的。但如果您不明白某些事情,请发表评论。我会回复的。

 if request.method=="POST":

    form = ReportSendMailForm(request.POST)

    if form.is_valid():

        email = form.cleaned_data['mail']
        message = form.cleaned_data['message']             
        print email
        print message
        result = export_pdf(request,id)
        file_to_be_sent= ContentFile(result)
        #print file_to_be_sent
        if result:
            #try :

                subject, from_email, to =  request.user.username+' has sent a report for review',' Dtz Team', email                   
                html_content = render_to_string('email/report.html',{'username':request.user,'messgae':message})                         
                msg = EmailMultiAlternatives(subject,'', from_email, [to])

                msg.attach_alternative(html_content, "text/html")
                msg.attach("Report.pdf", file_to_be_sent, "application/pdf")

                msg.send()  
                messages.success(request,'Please check your email id '+email+' for further instructions.')  
                return HttpResponse('success')         
            #except:
            #           pass             
messages.error(request,'Error occured in the pdf.')            
return HttpResponse(status=410)  

导出PDF功能

def export_pdf(request,id):
    report = Report.objects.get(id=id)                
    options1 = ReportPropertyOption.objects.filter(report=report,is_active=True)
    for option in options1:
        option.exterior_images = ReportExteriorImages.objects.filter(report = option)  
        option.interior_images = ReportInteriorImages.objects.filter(report = option)
        option.floorplan_images = ReportFloorPlanImages.objects.filter(report = option)
        option.fitouts =    ReportFitOut.objects.filter(propertyoption = option)   
        if (option.gps_longitude):
            option.map = "http://maps.google.com/maps/api/staticmap?zoom=12&size=400x400&maptype=roadmap&sensor=false&center=\""+str(option.gps_latidtude)+","+str(option.gps_longitude)+"\""                 

    html  = render_to_string('report/export.html', { 'pagesize' : 'A4', }, context_instance=RequestContext(request,{'options1':options1,'meta':report.meta}))
    result = StringIO.StringIO()       
    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), dest=result, link_callback=fetch_resources )
    if not pdf.err:
        return result
    else:
        return None
4

1 回答 1

4

你不应该使用django.core.files.ContentFile,它只接受字符串。

file_to_be_sent= export_pdf(request,id).getvalue() # if it's not None
msg.attach("Report.pdf", file_to_be_sent, "application/pdf")
于 2013-12-21T09:32:56.987 回答