打开基于URL的PDF

2024-04-18 20:02:36 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我的目标是让用户点击发票的链接,它会打开一个显示该发票的PDF的窗口。目前,我得到以下错误:

NoReverseMatch at /laptops/invoices/
Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/wordpress-pdf-invoice-plugin-sample.pdf'}' not found. 1 pattern(s) tried: ['laptops\\/invoices\\/(?P<invoice>[^/]+)\\/$'] 

糟糕的编程实践,我知道。我只是想在清理干净之前让它工作,但我不知道我做错了什么

网址.py

urlpatterns = [
    path('',views.laptop_list, name ="list"),
    path('add/',views.laptop_add,name="add"),
    path('invoices/', views.invoice_list,name="invoices"),
    path('invoices/<str:invoice>/', views.pdf_view, name ="pdfview")
]

视图.py

def pdf_view(request, invoice):
    invoicename=Laptop.objects.get(invoicename=invoice)
    pdfpath = settings.MEDIA_ROOT
    with open(pdfpath+'/'+invoicename, encoding="latin-1") as pdf:
        response = HttpResponse(pdf.read(), content_type='application/pdf')
        return response

笔记本电脑发票.html

<h2>View invoices</h2>
{%for i in invoices%}
<ul>
   <li>
       <a href = "{%url 'laptops:pdfview' invoice=i.invoice%}"> {{i.invoice}} </a>
   </li>
</ul>
{%endfor%}

Tags: pathnamepyaddforpdfwith发票