Django CBV:从媒体下载PDF文档

问题描述 投票:0回答:1

我想在我的视图中下载pdf文件,但我没有克服显示浏览器窗口,让我下载我的文件。

downloadPDF功能似乎运行良好,但我的浏览器上没有任何内容。

这是我的班级:

class TokenDownloadView(TemplateView):
    template_name = 'app/token.html'

    def get_context_data(self, **kwargs):
        now = timezone.now()
        context = super().get_context_data(**kwargs)
        context['token'] = self.kwargs['token']
        token = context['token']

        download = Download.objects.get(token__iexact=token)
        upload_doc = Document.objects.get(id=download.pub_id).upload

        if download and download.expiration_date > now:
            print("token valide jusqu'à : " + str(download.expiration_date))
            print("il est actuellement : " + str(now))
            print(' ==> Token existe et valide <==')
            messages.success(self.request, 'Vous allez télécharger le document')

            self.downloadPDF(upload_doc)

        if download and download.expiration_date < now:
            print("token valide jusqu'à : " + str(download.expiration_date))
            print("il est actuellement : " + str(now))
            print('==> Token existe mais a expiré <==')
            messages.error(self.request, 'Document non téléchargé : la session a expiré')

        return context

    def downloadPDF(self, upload_doc):

        from django.core.files.storage import FileSystemStorage
        from django.http import HttpResponse, HttpResponseNotFound

        fs = FileSystemStorage()
        filename = upload_doc
        if fs.exists(filename):
            with fs.open(filename) as pdf:
                response = HttpResponse(pdf, content_type='application/pdf')
                response['Content-Disposition'] = 'attachment; filename="mypdf.pdf"'
                return response
        else:
            return HttpResponseNotFound('The requested pdf was not found in our server.')

我想念课堂上可以下载我的pdf的东西吗?

编辑:

我编辑了我的课程,以便将get_context_data()转换为get()方法。它似乎工作,但我想了解你的想法:

class TokenDownloadView(TemplateView):
    template_name = 'app/token.html'

    def get(self, request, *args, **kwargs):
        now = timezone.now()
        context = super().get(request, *args, **kwargs)

        token = self.kwargs['token']

        download = Download.objects.get(token__iexact=token)
        document_title = Document.objects.get(id=download.pub_id).title
        upload_doc = Document.objects.get(id=download.pub_id).upload

        if download and download.expiration_date > now:
            print("Token is valid until : " + str(download.expiration_date))
            print("Now : " + str(now))
            print(' ==> Token exists and valid <==')
            messages.success(self.request, 'You are going to download document(s)')

            resp = self.downloadPDF(upload_doc, document_title)

        if download and download.expiration_date < now:
            print("Token is valid until : " + str(download.expiration_date))
            print("Now : " + str(now))
            print('==> Token exists but has expired <==')
            messages.error(self.request, 'Session of 10 minutes has expired - Please download document(s) one more time')
            return render(request, self.template_name)

        return resp

    def downloadPDF(self, upload_doc, document_title):

        fs = FileSystemStorage()
        filename = upload_doc
        if fs.exists(filename):
            with fs.open(filename) as pdf:
                response = HttpResponse(pdf, content_type='application/pdf')
                response['Content-Disposition'] = 'attachment; filename="%s.pdf"' % document_title
                return response
        else:
            return HttpResponseNotFound('The requested pdf was not found in our server.')
django
1个回答
1
投票

你调用downloadPDF但忽略了它的返回值。您需要返回调用该方法的结果。但是,这不起作用,因为您无法从get_context_data返回响应;顾名思义,该方法必须返回字典上下文而不是响应。

您需要将此代码移动到get方法中。

© www.soinside.com 2019 - 2024. All rights reserved.