Search code examples
pythondjangozippython-docx

How to add a temporary .docx file to a zip archive in django


here is my code for downloading a zip file, containing a .docx file,

def reportsdlserien(request):
    selected_sem = request.POST.get("semester","SS 2016")

    docx_title="Report_in_%s.docx" % selected_sem.replace(' ','_')

    document = Document()
    f = io.BytesIO()

    zip_title="Archive_in_%s.zip" % selected_sem.replace(' ','_')
    zip_arch = ZipFile( f, 'a' )

    document.add_heading("Report in "+selected_sem, 0)
    document.add_paragraph(date.today().strftime('%d %B %Y'))

    document.save(docx_title)
    zip_arch.write(docx_title)
    zip_arch.close()
    response = HttpResponse(
        f.getvalue(),
        content_type='application/zip'
    )
    response['Content-Disposition'] = 'attachment; filename=' + zip_title
    return response

the only problem is, it also creates the .docx file, which i dont need. I wanted to use BytesIO for a docx file too, but i cant add it to the archive, the command zip_arch.write(BytesIOdocxfile) doesn't work. Is there another command to do this? Thank you!


Solution

  • Use the writestr() function to add some bytes to the archive:

    data = StringIO()
    document.save(data)  # Or however the library requires you to do this.
    zip_arch.writestr(docx_title, bytes(data.getvalue()))
    

    I've only done this with StringIO, but I don't see why BytesIO would't work just as well.