表单重定向中的Django NoReverseMatch [英] Django NoReverseMatch in form redirect
问题描述
我遇到以下错误:
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: []
虽然我认为它与我的网址正则表达式或传递给 index.html
模板中的 views.py
.
I can't get to the bottom of it, though I think it has something to do with either my url regex or the document.slug
variable passed to the index.html
template in 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:
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:
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
错误,而不是重定向回创建的文档.新创建的文档在索引页面上列出,我可以通过单击该文档的链接来导航至该文档,它似乎以重定向形式抛出错误.
The form creates the new document fine, it shows up in the admin. But when I click on the forms save button it brings up the NoReverseMatch
error rather than redirecting back to the created document. The newly created document is listed on the index page and I can navigate to it by clicking on it's link there, it just appears to throw the error in the form redirect.
推荐答案
在调用 redirect
时,您省略了 lld
命名空间.使用 redirect
或 reverse
时,需要包括名称空间,与使用 {%url%}
时已经采用的方法相同.在模板中标记:
When calling redirect
, you have left out the lld
namespace. You need to include the namespace when you use redirect
or reverse
, the same way as you already do when you use the {% url %}
tag in your templates:
return redirect('lld:display_lld', slug=document.slug)
这篇关于表单重定向中的Django NoReverseMatch的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!