【问题标题】:Unexpected NoReverseMatch error when using include() in urls patterns在 url 模式中使用 include() 时出现意外的 NoReverseMatch 错误
【发布时间】:2018-03-17 13:42:55
【问题描述】:

index.html 中引用detail.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'

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'),
]

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 %}

detail.html

{% extends "index.html" %}

<iframe width="560" height="345" src="{{ feat.youtube_link }}"       frameborder="0" allowfullscreen></iframe>

项目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)

在我在index.html 的图像上添加&lt;a href= 之前,该应用运行良好。

不知道出了什么问题。

【问题讨论】:

    标签: python regex django


    【解决方案1】:

    这表明有问题。

    '$(?P<pk>[0-9]+)/$'
    

    模式的开头不应有美​​元符号(匹配字符串的结尾)。

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

    url(r'^$', include('feature.urls', namespace="feature")),
    

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

    url(r'^', include('feature.urls', namespace="feature")),
    

    【讨论】:

    • 对不起,我不明白。如您所见,urls.py 中的正则表达式前面没有美元。你要我做什么改变?我已经编辑了上面的代码,为项目添加了urls.py
    • 使用 include 时从正则表达式中删除美元符号,即url(r'^', include('feature.urls', namespace="feature")),
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-03
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多