Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

problem with render function #540

Open
ReynanVv opened this issue Apr 23, 2024 · 0 comments
Open

problem with render function #540

ReynanVv opened this issue Apr 23, 2024 · 0 comments

Comments

@ReynanVv
Copy link

I have an API in Django Rest Framework and encountered an issue with docxtpl. I'm using a template to be filled by a single render with a global context, converting the file to PDF, and sending it to my frontend to download the file. However, if I try to use the function more than once, the initially filled file has its data duplicated within the for loop of the template document. In other words, a table that is filled with a for loop in the template, which initially has one filled row, ends up with two duplicate rows. I think it has something to do with the render function. At some point, I thought I had solved it by setting the is_rendered flag to false before using the render function. It worked when I tested it, but I had tried so many things before that I have no idea what really solved it. When I shut down the Django server, it returns to normal. This means that the filled document works well when I try to download it for the first time, but it still doesn't work on the second attempt.

with io.BytesIO() as temp_docx_buffer:
        with open("myapp/doc/Modelo_RADOC.docx", 'rb') as file:
            conteudo_arquivo = file.read()

            with io.BytesIO() as arquivo_em_memoria:
                arquivo_em_memoria.truncate(0)
                arquivo_em_memoria = io.BytesIO(conteudo_arquivo)
                doc = DocxTemplate(arquivo_em_memoria)

        temp_docx_buffer.truncate(0)
        doc.is_rendered = False
        doc.render(global_context)
        doc.save(temp_docx_buffer)
        html_content = docx_to_html(temp_docx_buffer.getvalue())
        pdf_binary = convert_html_to_pdf(html_content)
    lista_atividades_letivas_1.clear()
    return pdf_binary

first download:
enter image description here

second download:
enter image description here

I made some modifications to the function, such as using the file entirely in memory. I also attempted to use Django's never_cache, clearsession, and even tried using a middleware to clear the session. Lastly, you experimented with setting the flag is_rendered = False

Git Hub Project

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant