我正在为类似维基百科的网站(CS50W 项目 1)编写 Django 项目。我的项目中有一个名为 encyclopedia 的应用程序。在这个应用程序的
views.py
文件中,我有一个重定向,为此我使用 django.urls.reverse()
函数。可以在here找到此功能的文档链接。
现在解决问题:如果用户访问
/wiki/file
文件不是有效页面,那么在 entry
视图中将找不到 markdown 文件。而且,正如您所看到的,它应该将您重定向到“未找到”页面。但是,代码 return HttpResponseRedirect(reverse("notfound"))
会无限期地将用户循环回 entry
视图,而不是将用户重定向到 not find页面。 到目前为止我找到了两种解决方案: 可以对 URL 模式重新排序,以便 notfound
模式出现在 entry 模式之前,或者可以向上述任一 URL 模式添加斜杠。 但是,我正在寻找问题的原因。我目前正在考虑
reverse()
函数出于某种原因使用 URL 模式而不是名称的可能性。
urls.py
百科全书文件:
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:title>", views.entry, name="entry"),
path("wiki/notfound", views.notfound, name="notfound"),
]
views.py
百科全书文件:
from django.shortcuts import render
import markdown2
from django.urls import reverse
from django.http import HttpResponseRedirect
from . import util
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def entry(request, title):
md = util.get_entry(title)
if md is None:
return HttpResponseRedirect(reverse("notfound"))
else:
html = markdown2.markdown(md)
return render(request, "encyclopedia/entry.html", {
"title": title,
"entry": html
})
def notfound(request):
return render(request, "encyclopedia/notfound.html")
reverse()
的警告。由于代码的工作方式,这只是一个有趣的结果。
reverse()
查找名称为 notfound的 URL 模式并将其返回为
/wiki/notfound
。然后 HttpResponseRedirect()
将用户重定向到该 URL,该 URL 恰好首先显示为 entry视图的 URL,将用户重定向回 entry 视图并重新启动该过程。永远不会到达 not find 页面,因为它的 URL 是其上方的 entry 视图的 URL 的子集。