我正在使用 django 开发一个 wiki 项目。 我尝试使用视图 add 渲染“add.html”,但它却将我发送到 404。所有其他视图都工作正常。我应该如何修复添加?
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
from django import forms
import re
from . import util
def index(request):
return render(request, "encyclopedia/index.html", {
"entries": util.list_entries()
})
def detail(request, entry):
#if search based on title returns result
if util.get_entry(entry):
content = util.get_entry(entry)
return render(request, "encyclopedia/details.html",
{
"title": entry,
"content": content
})
else:
return render(request, "encyclopedia/404.html", {
'entry': entry
})
def add(request):
return render(request, "encyclopedia/add.html")
urls.py:
from django.urls import path
from . import views
app_name = "wiki"
urlpatterns = [
path("", views.index, name="index"),
path("<str:entry>/", views.detail, name="entry"),
path("add/", views.add, name="add"),
]
在您的
urls.py
中,<str:entry>/
路径在 add/
路径之前定义。
这会导致 django 将
add/
解释为详细视图的动态条目参数,而不是将其路由到添加视图。
urlpatterns = [
path("", views.index, name="index"),
path("add/", views.add, name="add"), # place "add/" before "<str:entry>/"
path("<str:entry>/", views.detail, name="entry"),
]