Home > OS >  Is there a way to render a docx file using Django Template?
Is there a way to render a docx file using Django Template?

Time:10-12

I'm creating a function that takes two arguments: A list of documents, and a dictionary containing values with key names that matches the keywords in the documents, which are identified by two curly braces around them: {{Value}}. I'm supposed to combine all the documents into a single document and render this document using Django Template. Django would automatically read the keywords and replace them with the dictionary values. Simple as that, right? I suppose not, but i gotta ask.

Is there any way of doing this? Is this even possible?

Just to clarify, i already combined all documents into one, so it's only rendering it that is confusing me. Has anyone gone through a similar situation?

CodePudding user response:

You can use this library: https://docxtpl.readthedocs.io/en/latest/

pip install docxtpl

views.py
    from django.http import HttpResponse
    from docxtpl import DocxTemplate

    def render_docx(request):
        doc = DocxTemplate("your_docx_template.docx") 
        # you have to place your_docx_template.docx in the root of your project (same level as manage.py).
        
        context = {
        # ...
        }
    
        response = HttpResponse(content_type="application/vnd.openxmlformats-officedocument.wordprocessingml.document")
        response["Content-Disposition"] = 'filename="your_doc_name.docx"'
    
        doc.render(context)
        doc.save(response)
    
        return response
  • Related