So, I'm trying to pass the name of the PDF to the URL so that the view can display the relevant 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%}
Now, my question is: Why does it work when I use invoice='default.pdf' and not when I useinvoice=i.invoice? I get the following error
NoReverseMatch at /invoices/
Reverse for 'pdfview' with keyword arguments '{'invoice': 'uploads/default1.pdf'}' not found. 1 pattern(s) tried: ['show\\-invoice\\/(?P<invoice>[^/]+)$']