Generate PDF from view return

Hi all,

I have a django view that run another Python Script and it returns a variable with any data (text).

I need to generate a pdf file with this return above but I’m not finding a way to pass this variable to generate pdf view that I created.

Please, does anybody can help me?

Thanks!

We’ll need to see the view(s) here.

Hi Ken,

The view below is the first view that call another python script and it returns a text:

def scriptsdr(request):

if request.method == "POST":
    tipo_scripts = TiposScripts(request.POST)
    operadoras = Operadoras(request.POST)
    if tipo_scripts.is_valid() and operadoras.is_valid():
        tipo_de_script = tipo_scripts.cleaned_data["tipos_de_scripts"]
        operadora = operadoras.cleaned_data["operadoras"]

        #Chama a função dentro do diretório "services"
        ip = show_run.lista_de_equipamentos()
        algumacoisa = show_run.conectar(ip)
        #print(resposta)
        #return redirect('generate_pdf',resposta)
        return HttpResponseRedirect(reverse("tela_de_sucesso",algumacoisa))

else:
    tipo_scripts = TiposScripts()
    operadoras = Operadoras()

return render (request,'scriptsdr.html', {"tipo_scripts": tipo_scripts, "operadoras": operadoras})

The view below is to generate a PDF file with return above:

def generate_pdf(request, algumacoisa):
“”“Generate pdf.”""
# Model data
equipamentos = [algumacoisa,algumacoisa]

# Rendered
html_string = render_to_string('pdf.html', {'equipamentos': equipamentos})
html = HTML(string=html_string)
result = html.write_pdf()

# Creating http response
response = HttpResponse(content_type='application/pdf;')
response['Content-Disposition'] = 'inline; filename=list_equipamentos.pdf'
response['Content-Transfer-Encoding'] = 'binary'
with tempfile.NamedTemporaryFile(delete=True) as output:
    output.write(result)
    output.flush()
    output = open(output.name, 'rb')
    response.write(output.read())

return response

Thanks for help!!!

Ok, so you have a function named scriptsdr. It’s being used as a view, which means it accepts a request (and parameters) and returns an HttpResponse (or one of its variants). That’s the basic definition of a view.

You have a second function, generate_pdf. It’s also a view, accepting a request and returning an HttpResponse.

Using that second view from the first is a lot easier than you’re making it out to be. Your first function has a request (that was passed to it), and makes the parameters that the second view needs.

Since you have everything you need in the first function, you can call the second function directly, returning the results that it generates.

In other words, your return statement that is currently returning an HttpResponseRedirect could be return generate_pdf(request, algumacoisa)

Hi Ken,

I did it, and when I try to run the PDF (click on a button on HTML page that call this function), I see the error below. I already try pass the parameter but no success.

Please post the complete traceback as text. There’s not enough information in that snippet to provide enough context to suggest how to proceed.

Also please post the current views to show what you’ve done.

Finally, when posting code, templates, tracebacks, etc, enclose the lines between lines of three backtick - ` characters. This means you’ll have a line of ```, then your code (or whatever), then another line of ```. This directs the forum software to maintain the proper formatting of that code - which is particularly important with Python.

Hi Ken,

I have success now to pass a parameter to a generate pdf view as url parameter. It’s working.

However, this parameter is a very large text and when I send it, the error appears, I believe it is due to having invalid characters to form a URL. When I pass a simple string (Example: textstring) it works perfect.

Is there any way to pass this big text as a parameter? Or pass as a file?

Below the output when I try to pass a simple string:

[08/Jul/2021 15:56:36] "POST /scriptsdr/ HTTP/1.1" 302 0
[08/Jul/2021 15:56:36] "GET /scriptsdr/generate/pdf/MNBVBVBVBVBVBVV HTTP/1.1" 200 11907

Below the print of error when I try to pass a large string:

Thanks a lot!

The simple answer is no, you don’t want to do that.
Data beyond a certain size (and it depends upon factors outside the scope of Django), is only appropriately sent via POST and not GET.

What are you doing that is generating a GET of this size? (Whatever it is, you need to find a different way of achieving your desired result.)

I’m getting a cisco router configuration. All this output/configuration I already have inside an variable in the function that connect on Cisco router. Now I try to find a way to do put this content in a file and download it :frowning:

I’m sorry, in this situation I’m not looking for the Use Case for this - I’m looking for the specific code / process you’re using that is causing this to happen - that’s what’s needing to be changed.

Thanks for your attention!