Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
438 views
in Technique[技术] by (71.8m points)

python - Downloadable docx file in Django

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("test.docx", mimetype='application/vnd.ms-word')

However, it raises error like 'utf8' codec can't decode byte 0xeb in position 15: invalid continuation byte

I couldn't serve this file as static so I need to find a way to serve it as this. Really appreciate for any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Yep, a cleaner options, as stated by wardk would be, using https://python-docx.readthedocs.org/:

from docx import Document
from django.http import HttpResponse

def download_docx(request):
    document = Document()
    document.add_heading('Document Title', 0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=download.docx'
    document.save(response)

    return response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...