Search code examples
djangoms-worddocx

Filling MS Word Template from Django


I found some python docs relating to docxtpl at this link:

https://docxtpl.readthedocs.io/en/latest/

I followed the instruction and entered the code found at this site into a view and created the associated URL. When I go to the URL I would like for a doc to be generated - but I get an error that no HTTP response is being returned. I understand I am not defining one, but I am a bit confused about what HTTP response I need to define (I am still very new to this). The MS word template that I have saved is titled 'template.docx'.

Any help would be greatly appreciated!

VIEWS.PY

def doc_test(request):


    doc = DocxTemplate("template.docx")
    context = { 'ultimate_consignee' : "World company" }
    doc.render(context)
    doc.save("generated_doc.docx")

I would like accessing this view to generate the doc, where the variables are filled with what is defined in the context above.


Solution

  • Gist: Read the contents of the file and return the data in an HTTP response.


    First of all, you'll have to save the file in memory so that it's easier to read. Instead of saving to a file name like doc.save("generated_doc.docx"), you'll need to save it to a file-like object.

    Then read the contents of this file-like object and return it in an HTTP response.

    import io
    from django.http import HttpResponse
    
    
    def doc_test(request):
        doc = DocxTemplate("template.docx")
        # ... your other code ...
    
        doc_io = io.BytesIO() # create a file-like object
        doc.save(doc_io) # save data to file-like object
        doc_io.seek(0) # go to the beginning of the file-like object
    
        response = HttpResponse(doc_io.read())
    
        # Content-Disposition header makes a file downloadable
        response["Content-Disposition"] = "attachment; filename=generated_doc.docx"
    
        # Set the appropriate Content-Type for docx file
        response["Content-Type"] = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
    
        return response
    

    Note: This code may or may not work because I haven't tested it. But the general principle remains the same i.e. read the contents of the file and return it in an HTTP response with appropriate headers.

    So if this code doesn't work, maybe because the package you're using doesn't support writing to file-like objects or for some other reason, then it would be a good idea to ask the creator of the package or file an issue on their Github about how to read the contents of the file.