Home > database >  Display PDF in django
Display PDF in django

Time:11-28

I need to display a pdf file in a browser, but I cannot find the solution to take the PDF for the folder media, the PDF file was save in my database, but I cannot show.

my urls.py:

urlpatterns = [
    path('uploadfile/', views.uploadFile, name="uploadFile"),
    path('verPDF/<idtermsCondition>', views.verPDF, name='verPDF'),
]

my models.py:

class termsCondition(models.Model):

    title = models.CharField(max_length=20, verbose_name="title")
    uploadPDF = models.FileField(
        upload_to="PDF/", null=True, blank=True)
    dateTimeUploaded = models.DateTimeField(auto_now_add=True)

    deleted_at = models.DateTimeField(
        auto_now=False, verbose_name="Fecha eliminacion", blank=True, null=True)


class Meta:
    verbose_name = "termsCondition"
    verbose_name_plural = "termsConditions"

my views.py:

def uploadFile(request):
    user = request.user
    if user.is_authenticated:
        if user.is_admin:
            if request.method == "POST":
                # Fetching the form data
                fileTitle = request.POST["fileTitle"]
                loadPDF = request.FILES["uploadPDF"]

                # Saving the information in the database
                termscondition = termsCondition.objects.create(
                    title=fileTitle,
                    uploadPDF=loadPDF
                )
                termscondition.save()

            else:
                listfiles = termsCondition.objects.all()[:1].get()
                return render(request, 'subirTerminos.html', context={
                    "files": listfiles
                })
        else:
            messages.add_message(request=request, level=messages.SUCCESS,
                                 message="No tiene suficientes permisos para ingresar a esta página")
        return redirect('customer')

    else:
        return redirect('login2')



def verPDF(request, idtermsCondition):
    user = request.user
    if user.is_authenticated():
        if user.is_admin:
            getPDF = termsCondition.objects.get(pk=idtermsCondition)
            seePDF = {'PDF': getPDF.uploadPDF}
            print(seePDF)
            return render(request, 'subirTerminos.html', {'termsCondition': getPDF, 'uploadPDF': getPDF.uploadPDF})
        else:
            messages.error(request, 'Do not have permission')
    else:
        return redirect('login2')


my html:

<div>
    <iframe id="verPDF" src="media/PDF/{{ uploadPDF.url }}" 
    style="width:800px; height:800px;"></iframe>
  </div>

I want to see my pdf and I cannot do, I want to know how to do, I tried many solutions, I accept js, embed iframe whatever to can solve.

CodePudding user response:

It should be user.is_authenticated not user.is_authenticated() in verPDF view and also I'd recommend you to change <idtermsCondition> to <int:idtermsCondition> as by default (if nothing is given) it is considered as string.

urls.py

urlpatterns = [
    path('uploadfile/', views.uploadFile, name="uploadFile"),
    path('verPDF/<int:idtermsCondition>/', views.verPDF, name='verPDF'),
]

And the {{uploadPDF.url}} already has the url (full path to the media directory) and try to use <embed> tag so:

<div>
    <embed id="verPDF" src="{{uploadPDF.url}}" width="500" height="375" type="application/pdf">
</div>

Note: Always add / at the end of every route

CodePudding user response:

Finally I can solve it, I had problems in my views.py and in the html, when I called uploadPDF my views called another name which was loadpdf and when I rendered it it was another name.

now, views.py:

``def uploadFile(request):
        user = request.user
        if user.is_authenticated:
            if user.is_admin:
                if request.method == "POST":
                    # Fetching the form data
                    fileTitle = request.POST["fileTitle"]
                    loadPDF = request.FILES["uploadPDF"]
    
                    if termsCondition.objects.all().exists():
                        listfiles = termsCondition.objects.all()[:1].get()
                        listfiles.uploadPDF = loadPDF
                        listfiles.save()
                    else:
                        # Saving the information in the database
                        termscondition = termsCondition.objects.create(
                            title=fileTitle,
                            uploadPDF=loadPDF
                        )
                    return redirect('uploadFile')
                else:
                    if termsCondition.objects.all().exists():
                        listfiles = termsCondition.objects.all()[:1].get()
                        return render(request, 'subirTerminos.html', context={
                            "files": listfiles.uploadPDF
                        })
                    else:
                        listfiles = {}
                        return render(request, 'subirTerminos.html', context={"files": listfiles})
            else:
                messages.add_message(request=request, level=messages.SUCCESS,
                                     message="No tiene suficientes permisos para ingresar a esta página")
            return redirect('customer')
    
        else:
            return redirect('login2') ``
    
    and html:
    
        <h1 >Visualizador de PDF</h1>
            <embed id="verPDF" src="{{files.url}}" width="500" height="375" type="application/pdf">
  • Related