Django 在 PDF 导出中更改文件名

kft*_*ftb 1 python pdf django

我在Django Docs 中找到了这个方便的代码:

from reportlab.pdfgen import canvas
from django.http import HttpResponse

    def some_view(request):
        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

        # Create the PDF object, using the response object as its "file."
        p = canvas.Canvas(response)

        # Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        p.drawString(100, 100, "Hello world.")

        # Close the PDF object cleanly, and we're done.
        p.showPage()
        p.save()
        return response
Run Code Online (Sandbox Code Playgroud)

我想将一个变量作为变量名传递给函数,但无法弄清楚(尽管我确信这非常容易)。

有人有想法吗?

非常感谢!

小智 5

filename="somefilename.pdf"有一个地方可以确定您的文件名。您可以将其用作:

filename = 'somefilename.pdf'
response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
Run Code Online (Sandbox Code Playgroud)