我收到以下错误:
NoReverseMatch at /lld/new/
Reverse for 'display_lld' with arguments '()' and
keyword arguments '{'slug': u'stack-overflow-new-document'}' not found.
0 pattern(s) tried: []
我无法理解它,但我认为它与我的网址正则表达式或传递给document.slug
index.html
模板的views.py
变量有关。 }}
views.py:
from django.shortcuts import get_object_or_404, render, redirect
from .models import Document
from .forms import DocumentForm
def index(request):
document_list = Document.objects.order_by('-date_updated')
context = {'document_list': document_list}
return render(request, 'lld/index.html', context)
def display_lld(request, slug):
document = get_object_or_404(Document, slug=slug)
return render(request, 'lld/display_lld.html', {'document': document})
def new_lld(request):
if request.method == "POST":
form = DocumentForm(request.POST)
if form.is_valid():
document = form.save(commit=False)
document.save()
return redirect('display_lld', slug=document.slug)
else:
form = DocumentForm()
return render(request, 'lld/new_lld.html', {'form': form})
网站urls.py:
urlpatterns = [
url(r'^lld/', include('lld.urls', namespace="lld")),
url(r'^admin/', include(admin.site.urls)),
]
app urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
# example: /lld/
url(r'^$', views.index, name='index'),
# example: /lld/new/
url(r'^new/$', views.new_lld, name='new_lld'),
# ex: /lld/customername-projectname/
url(r'^(?P<slug>([\w-]+))/', views.display_lld, name='display_lld'),
]
的index.html:
{% if document_list %}
<ul>
{% for document in document_list %}
<li><a href="{% url 'lld:display_lld' document.slug %}">{{ document.customer }} / {{ document.title }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No documents are available.</p>
{% endif %}
<a href="{% url 'lld:new_lld' %}">Create New LLD</a>
表单创建新文档很好,它显示在管理员中。但是,当我单击表单保存按钮时,它会显示NoReverseMatch
错误,而不是重定向回创建的文档。新创建的文档列在索引页面上,我可以通过点击它的链接导航到它,它只是在重定向表单中抛出错误。
答案 0 :(得分:2)
调用redirect
时,您遗漏了lld
命名空间。您需要在使用redirect
或reverse
时包含命名空间,就像在模板中使用{% url %}
标记时一样:
return redirect('lld:display_lld', slug=document.slug)
答案 1 :(得分:1)
null