找不到NoReverseMatch模式

时间:2015-07-16 05:57:54

标签: python django

无法弄清楚为什么我会继续获得NoReverseMatch

应用/ url.py

from django.conf.urls import url, patterns

from . import views

urlpatterns = patterns('',
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P<contact_id>\d+)/detail/$', views.details, name='details'),


)

views.py

from django.core.urlresolvers import reverse
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.http import Http404
from django.views import generic

from django.template import RequestContext, loader

from .models import Person
# Create your views here.


class IndexView(generic.ListView):
    template_name = 'ContactManager/index.html'
    context_object_name = 'contact_list'

    def get_queryset(self):
        return Person.objects.order_by('lname')


def details(request, contact_id):
    contact = get_object_or_404(Person, id=contact_id)
    return render(request, 'ContactManager/details.html', {'contact': contact})

# class DetailView(generic.ListView):
#     model = Person
#     context_object_name = 'contact'
#     template_name = 'ContactManager/details.html'
#
#     def get_queryset(self):
#  

模板index.html

{% if contact_list %}
    <ul>
        {% for contact in contact_list %}
            <li>
               <a href="{% url 'contact:details' contact_id=contact.id %}"> {{ contact.fname }} &nbsp; {{ contact.lname }}</a>
            </li>
        {% endfor %}
    </ul>
{% else %}
    <p>You don't have any contacts currently.</p>
{% endif %}

我得到的错误:

Reverse for 'details' with arguments '()' and keyword arguments '{'contact_id': 1}' not found. 1 pattern(s) tried: ['$(?P<contact_id>\\d+)/detail/$']

我尝试在{% url ... %}中使用通用视图和一系列参数 任何帮助将非常感激。

2 个答案:

答案 0 :(得分:3)

我认为详细信息url模式有错误,错误消息中出现一个尝试过的模式,由$符号开始和结束:

  

尝试了1种模式:['$(?P \ d +)/ detail / $']

检查您的模式是否等于:

^(?P<contact_id>\\d+)/detail/$

如果这是正确的,请检查包含联系人网址的网址文件,如果类似,请执行以下操作:

url('^$', include(ContactManager.urls, namespace='contact'))

在prefix-pattern结尾处删除$符号:

url('^', include(ContactManager.urls, namespace='contact'))

答案 1 :(得分:0)

请注意,如果您未在name中定义urlpatterns,也会出现此错误。

做类似

的事情
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^error_containing_view/$', views.error_containing_view, name='error_containing_view'),
]

在您的应用中,urls.py会解决错误。