1

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>[^/]+)$']

1 Answer 1

2

Because the str converter you have used in the path does not match the \ in your invoice attribute.

You can use the path converter instead:

path('show-invoice/<path:invoice>', ...)
Sign up to request clarification or add additional context in comments.

1 Comment

Wow. Never would have picked up on that. Thanks, Daniel!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.