Search code examples
pythondjangopdfdjango-modelsdjango-views

How can I read a PDF file that is saved in the media folder in Django? I want to display it on an HTML page according to each id


I have developed a function within the views.py file. I made a for loop on that html page, but only this PDF file is the issue. The name, ID number, and other details all function flawlessly.

{% for i in prid %}
        <tr>
          <td>{{i.id}}</td>
          <td>{{i.help_name}}</td>
          <td>{{i.help_service}}</td>
          <td>{{i.help_budget}}</td>
          <td><a href="/pdfview/" target="_blank"  type="application/pdf" height="50px" width="20px">view file</a></td>
          <td>{{i.help_message}}</td>
          <td style="font-weight: bold;">{{i.help_status}}</td>
          <td id="click" ><a href="/adminprojectsurvey/?surveyid={{i.id}}"> click to survey</a></td>
        </tr>
        
        {% endfor %}




#in views.py

def admin_project(request):
    if request.method == 'GET':
        add = helpingtable.objects.all()
        return render(request,'admin/project.html',{'prid':add})
    else:
        return render(request,'admin/index.html')




these are my code,


Solution

  • This is the function I use. in my case I save the pdfs with my data rows id in their name, to be able to find them

    def My_Open_PDF_PK(request,pk):
    
       my_dir = settings.MEDIA_ROOT
    
       mypkdone= Pktestata.objects.get(id=pk)
    
       file_name_pdf =  my_dir + "/" + str(mypkdone.id) + " " + "Packing_List.pdf"
       File_Save_Name =  str(mypkdone.id) + " " + "Packing_List.pdf"  
    
       with open(file_name_pdf, 'rb') as pdf:
        
            response = HttpResponse(pdf.read(), 
            content_type='application/pdf')
            response['Content-Disposition'] = 'inline;filename=' +""+ File_Save_Name
            return response
    

    I hope it can be of help to you