【问题标题】:NoReverseMatch: Reverse for 'detail' not found. (Django Tutorials)NoReverseMatch:未找到“详细信息”的反向。 (Django 教程)
【发布时间】:2018-06-07 09:21:05
【问题描述】:

我一直在阅读 Django 2 教程。

我收到以下错误:

#Error:
#django.urls.exceptions.NoReverseMatch
#django.urls.exceptions.NoReverseMatch: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern #name.

进行了一些谷歌搜索并确认我已将我的视图命名为“详细信息”并且还命名了我的应用程序。

以下是我的代码。 请告诉什么是错的。我正在认真学习本教程,但这出现了。我怎样才能修复它与教程保持一致?谢谢!

文件: mysite/polls/templates/polls/index.html

{% for question in latest_question_list %}
        <li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
    {% endfor %}

mysite/polls/urls.py

app_name = 'polls'
urlpatterns = [
    path('', views.index, name='index'),
    # ex: /polls/
    # path('', views.index, name='index'),
    # ex: /polls/5/
    path('<int:question_id>/', views.detail, name='detail'),
    # ex: /polls/5/results/
    path('<int:question_id>/results/', views.results, name='results'),
    # ex: /polls/5/vote/
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

mysite/polls/views.py

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[:5]
    context = {'latest_question_list': latest_question_list}
    return render(request, 'polls/index.html', context)

补充: mysite/urls.py

urlpatterns = [
    path('polls/', include('polls.urls', namespace='polls')),
    path('admin/', admin.site.urls),
]

【问题讨论】:

  • views.detail在哪里?
  • def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question})
  • 我的整个 polls/views.py 文件:pastebin.com/su1kXEH4
  • 请推荐@gahan
  • 我的 settings.py 文件:pastebin.com/gxq5Hacq

标签: django python-3.x django-2.0


【解决方案1】:

您尚未在 views.py 文件中定义任何名为“detail”的函数。

添加此代码。

def detail(request, id):
    context = dict()
    return render(request, 'polls/index.html', context)

您还必须添加结果和投票功能。

从 index.html 文件中删除注释行。这些行中的语法不正确,Django 尝试在渲染之前解析注释行。

【讨论】:

  • 我确实添加了详细信息功能。这是我完整的 views.py 文件:pastebin.com/afc12wv3
  • django.urls.exceptions.NoReverseMatch django.urls.exceptions.NoReverseMatch:找不到“详细信息”的反向。 'detail' 不是有效的视图函数或模式名称。
【解决方案2】:

mysite/urls.py 中删除namespace,因为您已经指定了应用程序的app_name

或者你可以删除app_name并保留namespace(不确定这是否适用于Django 2.0,因为有some tweaks in app_name and namespace in this version)。

【讨论】:

    猜你喜欢
    • 2013-10-22
    • 1970-01-01
    • 2019-06-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2020-12-24
    • 2017-05-15
    • 2018-02-13
    相关资源
    最近更新 更多