[英]Cannot fix Django NoReverseMatch error despite URL being withing urls.py
在我詳細介紹 go 之前,這里是 html 文檔中導致錯誤的行,以及 views.py 和 urls.py:
<input class="search" type="text" name="q" placeholder="Search Encyclopedia" action="{% url 'encyclopedia:findpage' %}" method="get">
(是的, url
和'encyclopedia:findpage'
之間有一個空格)
views.py 查找頁面 function:
def findpage(request, name):
pages = util.list_entries()
wanted_pages = set()
wanted_page = None
for page in pages:
if not wanted_page and page == name:
wanted_page = util.get_entry(name)
continue
if name in page:
wanted_pages.add(page)
if wanted_page:
return render(request, 'encyclopedia/page.html', {
"title": name,
"entry": wanted_page
})
if wanted_pages and not wanted_page:
return render(request, 'encyclopedia/index.html', {
"entries": wanted_pages
})
else:
return render(request, 'encyclopedia/noresults.html')
網址.py:
from django.urls import path
from . import views
app_name = "encyclopedia"
urlpatterns = [
path("", views.index, name="index"),
path("<str:name>", views.wikipage, name="wikipage"),
path("<str:name>", views.findpage, name='findpage'),
path("create", views.newpage, name="newpage")
]
當我運行 Django 項目時,我在 / 處得到一個 NoReverseMatch。 網頁錯誤如下: In template /home/quinn/Desktop/cs50web/pset1/wiki/encyclopedia/templates/encyclopedia/layout.html, error at line 17 Reverse for 'findpage' with no arguments not found. 1 pattern(s) tried: ['(?P<name>[^/]+)$']
In template /home/quinn/Desktop/cs50web/pset1/wiki/encyclopedia/templates/encyclopedia/layout.html, error at line 17 Reverse for 'findpage' with no arguments not found. 1 pattern(s) tried: ['(?P<name>[^/]+)$']
第 17 行是我留在本頁頂部的 html 的一部分。 我檢查了許多來源以試圖解決此問題,但我無法弄清楚。
您需要指定一個名稱,因為您的 url 在這里需要它:
path("<str:name>", views.findpage, name='findpage')
您可以在模板的 url 標簽中指定 kwargs,如下所示:
{% url 'reverse:lookup' kwarg='insert here the value that needs to get passed in your url' %}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.