在urls模式中使用include()时出现意外的NoReverseMatch错误

Wut*_*Wut 1 python regex django

引用时,我得到一个错误detail.htmlindex.html

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

views.py

def rock_and_feat(request):
    feats = Feat.objects.order_by('-created')[:3]
    rocks = Rockinfo.objects.order_by('-rank')[:50]
    context = RequestContext(request, {
        'feats': feats, 'rocks': rocks
    })
    return render_to_response('template.html', context)


class DetailView(generic.DetailView):
    model = Feat
    template_name = 'feature/detail.html' 
    context_object_name = 'feat'
Run Code Online (Sandbox Code Playgroud)

urls.py

urlpatterns = [
    url(r'^$', views.rock_and_feat, name='rock_and_feat'),
    url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
Run Code Online (Sandbox Code Playgroud)

的index.html

{% extends "index.html" %}
{% block mainmast %}
<div id="wrapper">
{% if feats %}
{% for feat in feats %}
 <div class="specialsticky">
 <a href="{% url 'feature:detail' feat.id %}"><img src="{{ feat.image.url }}" alt="some text"></a>
  <h1 class="mast-header">
    <a href="#">{{feat.title}}</a>
  </h1>
 </div>

 {% endfor %}
 {% else %}
<p>No </p>
 {% endif %}
</div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)

detail.html

{% extends "index.html" %}

<iframe width="560" height="345" src="{{ feat.youtube_link }}"       frameborder="0" allowfullscreen></iframe>
Run Code Online (Sandbox Code Playgroud)

项目 urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static


urlpatterns = [
    url(r'^$', include('feature.urls', namespace="feature")),
    url(r'^admin/', include(admin.site.urls)),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Run Code Online (Sandbox Code Playgroud)

在我添加<a href= 图像之前,应用程序运行正常index.html.

无法弄清楚出了什么问题.

Ala*_*air 8

这表明了问题.

'$(?P<pk>[0-9]+)/$'
Run Code Online (Sandbox Code Playgroud)

在模式的开头不应该有一个美元符号(与字符串的末尾匹配).

问题是由您包含urls.py的方式引起的.您目前在正则表达式中有一美元:

url(r'^$', include('feature.urls', namespace="feature")),
Run Code Online (Sandbox Code Playgroud)

要解决此问题,请从正则表达式中删除美元.

url(r'^', include('feature.urls', namespace="feature")),
Run Code Online (Sandbox Code Playgroud)

  • 当你使用include时,从正则表达式中删除美元符号,即`url(r'^',include('feature.urls',namespace ="feature")),` (2认同)