所以,我正在尝试将PDF的名称传递给URL,以便视图可以显示相关的PDF。
urls.py
path('show-invoice/<str:invoice>', views.pdf_view, name ="pdfview")
views.py
def pdf_view(request, invoice):
invoicename = Laptop.objects.get(invoice=invoice)
invoicename = invoicename.invoice
pdfpath = settings.MEDIA_ROOT + invoicename
pdfpath = pdfpath.replace('/', '\\')
try:
return FileResponse(open(pdfpath, 'rb'), content_type='application/pdf')
except FileNotFoundError:
raise Http404()
models.py
invoice = models.FileField(default='default.pdf', upload_to='uploads/')
invoice_list.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%}
现在,我的问题是:为什么我在使用invoice='default.pdf'
而不是在使用invoice=i.invoice
时才有效?我收到以下错误
NoReverseMatch at /invoices/
Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/default1.pdf'}' not found. 1 pattern(s) tried: ['show\\-invoice\\/(?P<invoice>[^/]+)$']
答案 0 :(得分:2)