在我作為在線課程專案構建的 Django 應用程式中,我期望一個模板 (entry.html) 中的鏈接指向 urls.py 中的路徑(“edit”),url 中有一個變數。這應該在views.py 中啟動一個名為edit 的函式并渲染模板edit.html。
"Reverse for 'edit' with no arguments not found. 1 pattern(s) tried: ['wiki/(?P<entry>[^/] )/edit$']"單擊 entry.html 中的鏈接后,我收到 NoReverseMatch 錯誤 ( )。如果我在開發服務器中的 entry.html 上查看頁面源代碼,我可以看到 url 與 urls.py 中的匹配,但我仍然收到此錯誤。
在下面的示例中,“maggie”是entryTitle我嘗試傳遞的值。
條目.html:
{% block title %}
{{ entryTitle }}
{% endblock %}
{% block body %}
{{ entry|safe }}
<button>
<a href="{% url 'edit' entry=entryTitle %}">Edit Entry</a>
</button>
{% endblock %}
urls.py(列出的最后一個路徑是edit)
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("wiki/<str:entry>", views.entry, name="entry"),
path("search", views.search, name="search"),
path("new", views.new_page, name="new"),
path("wiki/<str:entry>/edit", views.edit, name="edit")
]
views.py 中的編輯功能
也顯示了我的entry功能
from django.http import HttpResponseRedirect
from django.urls import reverse
class EditPageForm(forms.Form):
content = forms.CharField(
widget=forms.Textarea(),
label="Edit Content:")
def edit(request, entry):
if request.method == "POST":
#Edit file and redirect
form = EditPageForm(request.POST)
if form.is_valid():
content = form.cleaned_data["content"]
util.save_entry(entry, content)
return HttpResponseRedirect(reverse('entry', kwargs={'entry': entry}))
else:
#Load form with initial values filled
content = util.get_entry(entry)
form = EditPageForm(initial={"content": content})
return render(request, "encyclopedia/edit.html", {
"editform": form,
"entryTitle": entry
})
def entry(request, entry):
markdowner = Markdown()
entryPage = util.get_entry(entry)
if entryPage is None:
return render(request, "encyclopedia/notfound.html", {
"entryTitle": entry
})
else:
return render(request, "encyclopedia/entry.html", {
"entry": markdowner.convert(entryPage),
"entryTitle": entry
})
Is anyone able to see what is causing this error with my code? I am surprised because when viewing page source, it seems that {% url 'edit entry=entryTitle %} is being correctly interpreted as wiki/maggie/edit , which is present in urls.py with maggie as <str:entry> and yet I am getting this error.
Here is a screenshot of page source:

uj5u.com熱心網友回復:
我洗掉了我之前的回答,我很抱歉。你應該讓你的生活更輕松并重組你的網址
path('wiki/edit/<str:entry>', views.edit, name="edit")
<button href="{% url 'edit' entry=entryTitle %}"></button>
這應該有效。
以前的方法是:
path('wiki/<str:entry>/edit', views.edit, name="edit')
我收到錯誤訊息:
Reverse for 'edit' with keyword arguments '{'entry': ''}' not found. 1 pattern(s) tried: ['so/wiki/(?P<entry>[^/] )/edit$']
我不知道為什么,但這與它是一個物件有關,因為傳入一個硬編碼的字串"maggie"而不是entryTitle作業正常。很抱歉所有的混亂。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/361108.html
下一篇:Django-多對多關系的經理
