Downloadable docx file in Django

前端 未结 4 749
慢半拍i
慢半拍i 2020-12-18 16:18

My django web app makes and save docx and I need to make it downloadable. I use simple render_to_response as below.

return render_to_response(\"         


        
4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 16:43

    I managed to generate a docx document from a django view thanks to python-docx.

    Here is an example. I hope it helps

    from django.http import HttpResponse
    from docx import Document
    from cStringIO import StringIO
    
    def your_view(request):
        document = Document()
        document.add_heading(u"My title", 0)
        # add more things to your document with python-docx
    
        f = StringIO()
        document.save(f)
        length = f.tell()
        f.seek(0)
        response = HttpResponse(
            f.getvalue(),
            content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )
        response['Content-Disposition'] = 'attachment; filename=example.docx'
        response['Content-Length'] = length
        return response
    

提交回复
热议问题