Search code examples
pythondjangoxhtml2pdf

405 error while generating a pdf in Django3


I followed this coadingforentrepreneurs tutorial to generate pdfs and it works fine.

The issue is when i use a post request to generate a pdf it shows me a 405 error. I am using post method to access customer-id to generate a invoice.

Here is my GeneratePDF class

class GeneratePDF(View):
    def get(self, request, *args, **kwargs):
        
            if request.method == 'POST':
                template = get_template('head/invoice.html')
                context = {
                "customer":"aaaa"
                }
                html = template.render(context)
                pdf = render_to_pdf('head/invoice.html', context)
                if pdf:
                    response = HttpResponse(pdf, content_type='application/pdf')
                    filename = "Invoice_%s.pdf" %("12341231")
                    content = "inline; filename='%s'" %(filename)
                    download = request.GET.get("download")
                if download:
                    content = "attachment; filename='%s'" %(filename)
                response['Content-Disposition'] = content
                return response
            
            template = get_template('head/invoice.html')
            context = {
                "customer":"aaaa"
            }
            html = template.render(context)
            pdf = render_to_pdf('head/invoice.html', context)
            if pdf:
                response = HttpResponse(pdf, content_type='application/pdf')
                filename = "Invoice_%s.pdf" %("12341231")
                content = "inline; filename='%s'" %(filename)
                download = request.GET.get("download")
                if download:
                    content = "attachment; filename='%s'" %(filename)
                response['Content-Disposition'] = content
                return response

I have not edited any other files

Here is the response from the server

Method Not Allowed (POST): /employee/customer_printbill/
Method Not Allowed: /employee/customer_printbill/

I am a beginner in django and i am unable to resolve this issue. Please help me out.


Solution

  • You're mixing function based and class based views. You should define post method in your class based view, and request will be dispatched to that post method. And thus you do not need to check if request.method is POST in your get method, because POST request will be handled by your post method. Please see Django Docs for more info.