Django - Reply with JsonResponse and pdf

1

I have a view that responds with a JsonResponse. I need to generate a pdf report using the same instance of the Building class (the structure variable).

For example, the view returned by a Json is:

   @login_required
    def buildings(request):
        if request.POST and request.is_ajax():
            s_form = BuildingForm(request.POST)
            if s_form.is_valid():
                structure = Building(**s_form.cleaned_data)
                html = render_to_string('wind/results/buildings/buildings_results.html', {'structure': structure})
                return JsonResponse({"result": html})
            else:
                return JsonResponse({'building_errors': s_form.errors,
                                    status=400)
        else:
            s_form = BuildingForm()
            return render(request, 'wind/buildings.html', {'s_form': s_form})

I have the following code to generate and return the pdf:

    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="Report.pdf"'
    buffer = BytesIO()
    report = BuildingsReport(structure)  # Quiero usar la misma instancia
    pdf = report.generate_pdf()
    response.write(pdf)
    return response

What I want is to use the same instance to generate as much as the html and the pdf.

Using a different view would imply making another instance of the Building class, unless there is some other solution making another view that I do not know.

In the browser I would like the html to be shown with the results and a button available for the user to download the pdf when he wants.

I have read some of Celery, but I do not finish understanding or discovering if it is adequate to do something like that.

Thanks in advance!

    
asked by Eduardo 04.10.2017 в 16:18
source

0 answers