通过循环传递参数

时间:2018-03-24 19:14:42

标签: python django

所以,我正在尝试将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>[^/]+)$']

1 个答案:

答案 0 :(得分:2)

由于您在路径中使用的str转换器与发票属性中的\不符。

您可以改为使用path转换器:

path('show-invoice/<path:invoice>', ...)