Python / Django generating PDF files using pdfkit


#1

I’m trying to generate a PDF document from an .html file using pdfkit (https://micropyramid.com/blog/how-to-create-pdf-files-in-python-using-pdfkit/) in my Django web app. I’m getting a “HTTP 405 error” when I click the “Download as PDF” button in detail.html . Could someone please advise where I’m going wrong.

views.py:

from django.template.loader import get_template
import pdfkit

def pdf(request):

if request.method == 'POST':

    ros = ResearchOutput.objects.all()
    template = get_template('detail.html')
    html = template.render({'ros': ros})
    options = {
        'page-size': 'Letter',
        'encoding': "UTF-8",
    }
    pdf = pdfkit.from_string(html, False, options)
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="person.pdf"'
    return response

detail.html:

<form action="" method="post">
{% csrf_token %}
<input type="submit" value="Download as PDF">

Thanks
Regards
R. Azharuddin
[Python Developer](https://mindmajix.com/python-training)

#2

I was going to recommend you post this on Stack Overflow, but I see you already have.

As mentioned there, you must not have configured the route/endpoint for posting. I’m not experienced with Django, but check your views file and make sure you have a def post for that page.

I’m also not sure of the importance of indentation but it looks like you may want to add an indent level to the if statement.

def pdf(request):
    
    if request.method == 'POST':
        
        ros = ResearchOutput.objects.all()
        template = get_template('detail.html')
        html = template.render({'ros': ros})
        options = {
            'page-size': 'Letter',
            'encoding': "UTF-8",
        }
        
        pdf = pdfkit.from_string(html, False, options)
        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="person.pdf"'
        
        return response
    
    else:
        
        //...