Search code examples
pythondjangopdfreportlab

Django reportlabs didn't return HttpResponse Object


I am trying to generate a pdf using reportlabs and I am encountering a The view APP.VIEW didn't return an HttpResponse object. error.

The function and view runs without any exceptions, even the line return HttpResponse(result.getvalue(), mimetype='application/pdf'). But I keep getting the error.

Below is my code:

def render_to_pdf(template_src, context_dict):
    """Function to render html template into a pdf file"""
    template = get_template(template_src)
    context = Context(context_dict)
    html  = template.render(context)
    result = StringIO.StringIO()

    pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("UTF-8")), result)
    if not pdf.err:
        return HttpResponse(result.getvalue(), mimetype='application/pdf')
    return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))

The view:

def invoice_pdf(request, inv_no):
    try:

        inv = BC_Invoice.objects.select_related().get(invoice_no=inv_no)

        render_to_pdf('bc_invoice_pdf.html', {'pagesize': 'A4',
                                          'inv': inv}
                                          )

    except Exception, e:
        pass
        HttpResponse(None)

Solution

  • You aren't returning anything from the view. You can't just call render_to_pdf or HttpResponse - you actually have to return the result.