朋友们,我几天都在努力解决NoReverseMatch错误,我似乎无法找到代码的错误。我必须说我对Django很新,所以如果你解释一下这个问题的解决方案我会非常感激,所以我可以从中学习:)
错误
NoReverseMatch at /david/Physics/
Reverse for 'subcategory' with keyword arguments '{'subcategory_name': 'a'}' not found. 1 pattern(s) tried: ['david/([a-zA-Z_]+)/(?P<subcategory_name>[a-zA-Z_]+)/$']
category.html:
<h1>The subcategories for {{ category }}</h1>
{% if subcategories %}
<ul>
{% for subcategory in subcategories %}
<li><a href="{% url 'subcategory' subcategory_name=subcategory %}">{{ subcategory }}</a></li>
{% endfor %}
</ul>
{% else %}
<h4>No subcategories for that category</h4>
{% endif %}
urls.py:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^search/$', views.search, name='search'),
url(r'^browse/$', views.browse, name='browse'),
url(r'^(?P<category_name>[a-zA-Z_]+)/$', views.view_category, name='category'),
url(r'^([a-zA-Z_]+)/(?P<subcategory_name>[a-zA-Z_]+)/$',
views.view_subcategory, name='subcategory'),
url(r'^([a-zA-Z_]+)/([a-zA-Z_]+)/(?P<information>[a-zA-Z_]+)/$',
views.view_information, name='information'),
]
views.py:
from django.shortcuts import render, get_list_or_404, get_object_or_404
from django.http import HttpResponse
from .models import Category, Subcategory
# Create your views here.
def index(request):
return render(request, 'basic_web/index.html')
def search(request):
return HttpResponse('Here you can search!')
def browse(request):
categories = Category.objects.all()
context = {'categories': categories}
return render(request, 'basic_web/browse.html', context)
def view_category(request, category_name):
category = get_object_or_404(Category,name__iexact=category_name)
subcategories = get_list_or_404(Subcategory, parent=category)
context = {'subcategories': map(lambda x: str(x), subcategories)}
return render(request, 'basic_web/category.html', context)
def view_subcategory(request, subcategory_name):
return HttpResponse('You are now browsing subcategory %s' % subcategory_name)
def view_information(request, information):
return HttpResponse('You are now seeing %s' % information)
如果我需要提供更多信息,请告诉我:) 希望你能帮帮我。
答案 0 :(得分:0)
您的子类别网址格式中有两个捕获组(信息中有三个)。这意味着它匹配如下:
/param1/subcategory_name/
您没有为第一个组指定名称,并且您没有在{% url %}
标记中传递该名称。你确定要的吗?您应该删除它,以便您的模式变为
r'^(?P<subcategory_name>[a-zA-Z_]+)/$',
如果另一方面你确实需要它,你应该给它一个名字:
url(r'^(?P<param_name>[a-zA-Z_]+)/(?P<subcategory_name>[a-zA-Z_]+)/$',
并在需要网址时传递:
{% url 'subcategory' param_name=param subcategory_name=subcategory %}
也许第一个参数是类别?