点击发票链接打开PDF窗口时遭遇NoReverseMatch错误求助
Hey there, let's break down why you're hitting this NoReverseMatch error and get that PDF popup working quickly (since you mentioned prioritizing functionality over optimization right now).
What's Causing the Error?
Your URL pattern laptops/invoices/(?P<invoice>[^/]+)/$ uses the regex [^/]+, which only matches strings without any slashes (/). But you're passing invoice='uploads/wordpress-pdf-invoice-plugin-sample.pdf'—this has a slash in it, so the regex can't match the pattern, hence the "reverse not found" error.
Quick Fixes to Get It Working Now
Here are two straightforward ways to resolve this immediately:
Option 1: Pass Only the Filename (Cleaner, Even for Quick Implementation)
Chances are, your pdfview view only needs the filename to locate the PDF in your uploads directory, not the full path. Adjust the value you pass to the reverse function:
If using Django templates:
Replace code like this:<a href="{% url 'pdfview' invoice=invoice.file.path %}">View Invoice</a>With this (using the
basenamefilter to grab just the filename):<a href="{% url 'pdfview' invoice=invoice.file.name|basename %}">View Invoice</a>If you don't have the
basenamefilter available, split the path manually:<a href="{% url 'pdfview' invoice=invoice.file.name.split('/')|last %}">View Invoice</a>If using
reverse()in a view:
Replace code like this:from django.urls import reverse pdf_url = reverse('pdfview', kwargs={'invoice': invoice.file.path})With this (using
os.path.basenameto extract the filename):import os from django.urls import reverse pdf_url = reverse('pdfview', kwargs={'invoice': os.path.basename(invoice.file.path)})
Option 2: Update the URL Pattern to Allow Slashes (Quickest, Less Clean)
If you really need to pass the full path with slashes, modify your URL pattern to accept any characters (including slashes):
Using Django's
path()syntax:from django.urls import path from . import views urlpatterns = [ # ... other patterns path('laptops/invoices/<path:invoice>/', views.pdfview, name='pdfview'), ]Using regex (
re_path()):from django.urls import re_path from . import views urlpatterns = [ # ... other patterns re_path(r'laptops/invoices/(?P<invoice>.+)/$', views.pdfview, name='pdfview'), ]This will let the
invoiceparameter include slashes, so your original reverse call will work.
A Quick Note for Future Optimization
While we're focusing on getting it working first, keep in mind that passing full file paths in URLs isn't ideal—it exposes your server's file structure and can lead to security risks. Once you have the popup working, consider switching to using a unique file ID or slug instead of the filename/path.
内容的提问来源于stack exchange,提问作者Reez0

