gpt4 book ai didi

python - 通过循环通过 URL 传递参数

转载 作者:行者123 更新时间:2023-12-01 02:02:22 25 4
gpt4 key购买 nike

因此,我尝试将 PDF 的名称传递给 URL,以便 View 可以显示相关的 PDF。

url.py

path('show-invoice/<str:invoice>', views.pdf_view, name ="pdfview")

View .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()

模型.py

invoice = models.FileField(default='default.pdf', upload_to='uploads/')

发票列表.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>[^/]+)$']

最佳答案

因为您在路径中使用的 str 转换器与发票属性中的 \ 不匹配。

您可以使用path转换器:

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

关于python - 通过循环通过 URL 传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49468815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com