Django NoReverseMatch

时间:2015-07-20 18:30:30

标签: python django

我无法理解什么是错的?我尝试制作一个项目的详细信息页面,例如http://tutorial.djangogirls.org/en/extend_your_application/index.html上的示例 它在我的项目中不起作用,但在练习中一切都很好。

错误消息: NoReverseMatch at /

Reverse for 'events.views.event_detail' with arguments '()' and keyword arguments '{u'pk': 3}' not found. 1 pattern(s) tried: ['$event/(?P<pk>[0-9]+)/$']

HTML(片段)

<div class="col-xs-6"><a class="btn btn-primary" href="{% url 'events.views.event_detail' pk=event.pk %}">Read more</a></div>
         </div>

settings.py

ROOT_URLCONF = 'mysite.urls' 

app urls.py

from django.conf.urls import include, url
from . import views

urlpatterns = [
    url(r'^$', views.events_list),
    url(r'^event/(?P<pk>[0-9]+)/$', views.event_detail),
]

app views.py

from django.shortcuts import render, get_object_or_404
from django.utils import timezone
from .models import Event

def events_list(request):
    events = Event.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'events/events_list.html', {'events': events})

def event_detail(request, pk):
    event = Event.objects.get(pk=pk)
    return render(request, 'events/event_detail.html', {'event': event})

1 个答案:

答案 0 :(得分:9)

您还没有展示您的mysite.urls,但是从错误消息中看起来您已经做过类似的事情:

(r'^events/$', include('events.urls')),

你需要删除终止$,因为这意味着正则表达式的结束;那之后什么都不匹配。它应该是:

(r'^events/', include('events.urls')),

请注意,您还应该提供事件网址名称,以便更容易引用:

url(r'^$', views.events_list, name='events_list'),
url(r'^event/(?P<pk>[0-9]+)/$', views.event_detail, name='event_detail'),

这样你就可以了:

{% url 'event_detail' pk=event.pk %}