【问题标题】:Getting NoReverseMatch Error出现 NoReverseMatch 错误
【发布时间】:2016-11-16 23:24:55
【问题描述】:

我有一个应用程序将显示有关我组中人员的一些信息。尝试在我的 index.html 中使用 url 标记时出现 NoReverseMatch 错误。如果我不使用 url 标记,而是指定根,我不会收到错误。

错误提示:

NoReverseMatch 在 / 未找到带有参数“(1,)”和关键字参数“{}”的“专家”的反向操作。尝试了 1 种模式:['$(?P[0-9]+)/']

这是 urls.py 文件。

来自主要的 wi_tech urls.py:

from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
    url(r'^$', include('person.urls')),
    url(r'^tech/', include('person.urls')),
    url(r'^admin/', admin.site.urls),
]

来自“人”应用 urls.py:

from django.conf.urls import url
from . import views
app_name = 'person'
urlpatterns = [
     url(r'^$', views.IndexView.as_view(), name='index'),
     url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='specialist'),
]

我的 views.py 文件如下所示:

from django.views import generic
from .models import Specialist
class IndexView(generic.ListView):
    template_name = 'person/index.html'
    context_object_name = 'person_list'

    def get_queryset(self):
        """Return all specialists"""
        return Specialist.objects.order_by('id')
class DetailView(generic.DetailView):
    model = Specialist
    template_name = 'person/detail.html'

我的 index.html 页面如下所示:

{% if person_list %}
    <ul>
    {% for specialist in person_list %}
        <li><a href="{% url 'person:specialist' specialist.id %}"> {{ specialist }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No specialists are available.</p>
{% endif %}

如果我将 index.html 中的标签更改为此,它可以工作:

<li><a href="/tech/{{specialist.id}}"> {{ specialist }}</a></li>

显然,万一网络根目录发生变化,这不是一个理想的情况。我已经审查了很多关于此的 SO 问题,但似乎没有任何匹配项。我认为问题出在正则表达式开头的“$”,但我不知道这是从哪里来的。

具体来说,我使用这个链接作为一个非常好的参考点,但是通过我的代码来看却是空洞的。 what is NoReverseMatch and how do i fix it

显然我缺少一些东西。

【问题讨论】:

  • 您是否尝试过以下更改以包括:url(r'^tech/', include('person.urls', namespace='person')),?
  • 为什么要包含person.urls 两次?第一个包含使用^$,这会导致您看到的错误。
  • @schwobaseggl namespace 默认使用 app_name,所以这绝对没有效果。
  • @knbk - 这绝对是我的问题。我需要为朴素的 url(^$ 用例)找出另一种解决方案。删除该行允许反向匹配工作。

标签: python django


【解决方案1】:

可能是网址末尾的附加 / 吗?

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

主键修饰符之后的那个。当您单击 URL(带有 (% url ':' model.name %))时,浏览器中会出现什么 URL?

【讨论】:

    【解决方案2】:

    我最终放弃了这个实现,并采用了一个更扁平的结构,所有模型、视图和模板都在同一个应用程序中。我在新设计中没有遇到过这个问题。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    相关资源
    最近更新 更多