Django CBV:从媒体下载PDF文档

时间:2018-09-12 09:49:30

标签: django

我想下载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.')

1 个答案:

答案 0 :(得分:1)

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

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