Django - NoReverseMatch

时间:2015-02-25 14:51:23

标签: python django

因此,我试图通过遵循基础教程进入Django,但更改它但是要实现我实际使用的东西。

我有这些urls.py:

from django.conf.urls import patterns, url
from budget import views

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^category/$', views.category, name='category'),
    url(r'^category/(?P<category_id>\d+)/$', views.category_detail, name='category_details')
)

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    url(r'^budget/', include('budget.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

然后我有以下模板:

{% if all_categories_list %}
    <ul>
    {% for category in all_categories_list %}
        <li><a href="/budget/category/{{category.id}}/">{{ category.category_text }}</a></li>
    {% endfor %}
    </ul>

这来自views.py

def category(request):
    all_categories_list = Budget_category.objects.order_by('category_type')
    context = {'all_categories_list': all_categories_list}
    return render(request, 'budget/category_list.html', context)

现在我要做的是从模板中删除硬编码/预算/类别/并将其替换为url关键字,以使其更灵活。

因此,请将模板中的行更改为此

<li><a href="{% url 'category' category.id %}">{{ category.category_text }}</a></li>

但是这会在localhost / budget / category /

上出现类型错误
NoReverseMatch at /budget/category/
Reverse for 'category' with arguments '(1,)' and keyword arguments '{}' not found. 1 pattern(s) tried: ['budget/category/$']

现在我知道这与命名空间或正则表达式有关(至少我是这么认为)但我似乎还没有足够的洞察力来看问题。导致此链接localhost / budget / category / 1 /确实以它应该的方式工作。那么为什么不能正确建立这种联系呢?

1 个答案:

答案 0 :(得分:3)

您的网址名称为category_details,而不是category。因此,请将{% url %}标记更改为:

{% url 'category_details' category.id %}