Google OAuth 登录后“问题”视图出现 Django NoReverseMatch 错误

问题描述 投票:0回答:1

我正在开发一个实施了 Google OAuth 的 Django 项目。主页 (index.html) 加载正确,并且 Google OAuth 登录按预期运行。但是,我在登录后尝试重定向到问题视图时遇到 NoReverseMatch 错误。

错误信息:

NoReverseMatch at /
Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name.
...
NoReverseMatch at /
Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name.
Request Method: GET
Request URL:    http://8000-lmcrean-classroommatrix-zp6cz7sdhxw.ws-eu106.gitpod.io/
Django Version: 3.2.23
Exception Type: NoReverseMatch
Exception Value:    
Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name.
Exception Location: /workspace/.pip-modules/lib/python3.9/site-packages/django/urls/resolvers.py, line 698, in _reverse_with_prefix
Python Executable:  /home/gitpod/.pyenv/versions/3.9.17/bin/python3
Python Version: 3.9.17
[...]

Error during template rendering

In template /workspace/Classroom-Matrix/templates/base.html, error at line 45

Reverse for 'questions' not found. 'questions' is not a valid view function or pattern name.
[...]
45                          <a class="nav-link" href="{% url 'questions' %}">Top Questions</a>

调试步骤

下面我回顾了问题领域并尝试解决调整。

模板/base.html

将第 45 行中的

'questions'
更改为
'index'
时,会出现相同的错误消息。至热门问题 - 导致
" 'index' is not a valid view function or pattern name."

似乎不太可能是问题的根源。

博客/urls.py

from . import views
from django.urls import path


urlpatterns = [
    path('', views.PostList.as_view(), name='home'),
    path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
    path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'),
]

这是一个很可能出现问题的领域,我目前正在调查创建

'questions/'
路径

python django django-views django-templates django-urls
1个回答
0
投票

通过在 blog/urls.py 中正确配置 URL 模式解决了 Django 中“问题”视图的 NoReverseMatch 错误问题。

发生错误是因为 Django 找不到名为“questions”的 URL 模式。通过向 blog/urls.py 中的 urlpatterns 列表添加相应的路径解决了这个问题。添加的路径将请求定向到适当的视图函数,在本例中为

PostList.as_view()

# Corrected urlpatterns in blog/urls.py
urlpatterns = [
    path('', views.PostList.as_view(), name='home'),
    path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'),
    path('like/<slug:slug>', views.PostLike.as_view(), name='post_like'),
    path('questions/', views.PostList.as_view(), name='questions'),
]

代码现在在 OAuth 登录后显示正确的视图。

© www.soinside.com 2019 - 2024. All rights reserved.